diff --git a/.ipynb_checkpoints/raremodel-nb-checkpoint.ipynb b/.ipynb_checkpoints/raremodel-nb-checkpoint.ipynb index b2495bc..294020b 100644 --- a/.ipynb_checkpoints/raremodel-nb-checkpoint.ipynb +++ b/.ipynb_checkpoints/raremodel-nb-checkpoint.ipynb @@ -850,11 +850,19 @@ "\n", "# calcs = zfit.run(total_test_tf(x_part))\n", "\n", + "\n", + "\n", "test_q = np.linspace(x_min, x_max, int(2e6))\n", "\n", "probs = total_f_fit.pdf(test_q, norm_range=False)\n", "\n", "calcs_test = zfit.run(probs)\n", + "\n", + "Ctt.set_value(0.5)\n", + "\n", + "probs1 = total_f_fit.pdf(test_q, norm_range=False)\n", + "\n", + "calcs_test1 = zfit.run(probs)\n", "# res_y = zfit.run(jpsi_res(test_q))\n", "# b0 = [b0_0, b0_1, b0_2]\n", "# bplus = [bplus_0, bplus_1, bplus_2]\n", @@ -873,15 +881,15 @@ "name": "stderr", "output_type": "stream", "text": [ - "C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\ipykernel_launcher.py:12: UserWarning: Creating legend with loc=\"best\" can be slow with large amounts of data.\n", - " if sys.path[0] == '':\n", + "C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\ipykernel_launcher.py:13: UserWarning: Creating legend with loc=\"best\" can be slow with large amounts of data.\n", + " del sys.path[0]\n", "C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\IPython\\core\\pylabtools.py:128: UserWarning: Creating legend with loc=\"best\" can be slow with large amounts of data.\n", " fig.canvas.print_figure(bytes_io, **kw)\n" ] }, { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAaUAAAD4CAYAAABMtfkzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAgAElEQVR4nO29eXzc1XX3/z4zo9Eu2dq825JtGSMbsxmbHWM2k5CYJqRxElJSaMmTkrZJnjxNaJukTeH3lLZPaNKsvGISsmEoIcEhBIdgUwIYY4MNeMWyvMmbVkvWrpm5vz++d0bj0ayypBlJ5/16+eWZO/d77p2vre9H59xzzxVjDIqiKIqSCbjSPQFFURRFCaKipCiKomQMKkqKoihKxqCipCiKomQMKkqKoihKxuBJ9wQyjbKyMlNZWZnuaShKxrP35BkKsj3MnJx7Vvvprj6OtnazYEoh2Z70/t6781gbZYXZTC3KoaWzj2Onuzl/WhEel6R1XuORN998s8kYU36udlSUIqisrGTbtm3pnoaiZDzLHvwDKxdW8K8fXnJW+zM7jvG363bwqy9cx/yKgjTNzmHe3z/H/7puLv/nloX8YssR/v5X77Lh729gSlFOWuc1HhGRw8NhR8N3iqIMiYABVxSPw23bAhmwB9IYg0uc+QSn6g+kf15KbFSUFEUZEgFjiBYFc1sRyISHf8BAcIquDBJLJTYqSoqiDImAMSEBCifoKaVblILVaiTkKYltT9uUlCTQNSVFUYaEP2BCD/xwMkeUnL+DU0xX+K6/v5/6+np6enpGddyRIicnh5kzZ5KVlTUi9lWUFEUZEsYMCFA4wTCZP80uSXB0sQG8dK111dfXU1hYSGVlZVQRH0sYY2hubqa+vp6qqqoRGUPDd4qiDAl/IP6aUiDtnpIzfnCOQUEY7Wn19PRQWlo65gUJnHtYWlo6ol6fipKiKEMiYEzU7DtPhoTvAjHCd+lIdBgPghRkpL+LipKiKEMiEJZuHY4rQ0TJcHaiQ8iD00yHjEZFSVGUIeEPJMi+S/eaUoSnJBmUqp6JvPTSS9x2220A9Pb2cuONN3LRRRfxxBNPjOo8NNFBUZQhEWvzrCtDHv4hUYpIdFBHKTHbt2+nv7+fHTt2jPrYSXlKIrJKRPaJSK2IfDnK59ki8oT9fIuIVIZ9dr9t3ycitySyKSJV1sZ+a9MbbwwRKRWRTSLSISLfjjH/9SKyM7lboihKIoJJDNESHTwZskk1GL5zZcCaUro5dOgQCxcu5K677mLJkiXccccddHV18fzzz7Nw4UKuvvpqnn76aQAaGhq488472bFjBxdddBEHDhwY1bkm9JRExA18B7gJqAe2ish6Y8zusG73AK3GmPkisgZ4CPioiNQAa4BFwHTgDyKywF4Ty+ZDwMPGmHUi8n1r+3uxxgB6gK8Ai+2fyPl/COhI6a4oihKX4IM9XvjO58+0RIf0e3D//Jtd7D7ePqw2a6YX8bUPLErYb9++faxdu5arrrqKu+++m2984xv84Ac/YOPGjcyfP5+PfvSjAFRUVPDDH/6Q//iP/+DZZ58d1rkmQzKe0jKg1hhTZ4zpA9YBqyP6rAYes6+fAm4QJ4C7GlhnjOk1xhwEaq29qDbtNSutDazN2+ONYYzpNMa8giNOZyEiBcAXgAeS+J6KoiRJcL0oXvgu3R7JQEq4regQ8uDSNqW0MmvWLK666ioA7rzzTrZt20ZVVRXV1dWICHfeeWeaZ+iQzJrSDOBo2Pt6YHmsPsYYn4i0AaW2/fWIa2fY19FslgKnjTG+KP1jjdEUZ+7/Avw/oCveFxSRe4F7AWbPnh2vq6IoDKzLRMu+G6joMJozGkyk+AT106RRLJPxaEaKyFTutra2jExVT8ZTijbryH/VWH2Gqz3ZeQxMSOQiYL4x5lex+oSMGPOIMWapMWZpefk5HweiKOMef5w1pUzJviMUvju79l26EzDSxZEjR9i8eTMAjz/+ODfeeCMHDx4MrRk9/vjj6ZxeiGREqR6YFfZ+JnA8Vh8R8QDFQEuca2O1NwGTrI3IsWKNEYsrgEtF5BDwCrBARF6K+00VRUkKn32wRyszNOAppddVGpzoMLHDd+effz6PPfYYS5YsoaWlhc9//vM88sgjvP/97+fqq69mzpw56Z4ikFz4bitQLSJVwDGcxIWPR/RZD9wFbAbuADYaY4yIrAd+ISLfwEl0qAbewPF6Btm012yyNtZZm8/EGyPWpI0x38NJkMBm6j1rjFmRxPdVFCUBwey7aCe4DhxdMapTGkQo0cG+n8jZdwAul4vvf//7Z7WtWrWKvXv3Duq7YsUKVqxYMUozO5uEomTXbz4LbADcwKPGmF0i8nVgmzFmPbAW+KmI1OJ4L2vstbtE5ElgN+AD7jPG+AGi2bRDfglYJyIPANutbWKNYW0dAooAr4jcDtwckR2oKMowEs9Tctn4S8bUvnOltyCrkhpJbZ41xjwHPBfR9tWw1z3AR2Jc+yDwYDI2bXsdTnZeZHu8MSoTzP8QUdLFFUUZGqGUcNfgFQCPbUv3mlKkp5SugqyZQGVlJTt3jo2tmlpmSFGUlBnwlAZ/FtQpX7o9pYFMByAsfJeGeaUz42+4GenvoqKkKErKBAKxPaVMOboiqElBMUpX+C4nJ4fm5uZxIUzB85RycnJGbAytfacoSsrE85Qy5eTZgfDd2Snhoz2tmTNnUl9fT2Nj4+gOPEIET54dKVSUFEVJGX88TylDEgoiU8KD+0RHWyyzsrJG7JTW8YiG7xRFSZmQKMWrfZcpnlJE+G48hNHGMypKiqKkjD9eSniGVE4Iik9k+C7dWYFKfFSUFEVJmXiiFArfpV2UnL8jq4SnO/9CiY+KkqIoKRP0NuJWdEj3mtKg2nfBdlWlTEZFSVGUlAnWtYt6dIVLEMmA8F2M2nfpnpcSHxUlRVFSJljXLlqiQ7A93Q//WIkOqkmZjYqSoigp47OeUrQ1JXC8pfSH785OdAiKU7pT1ZX4qCgpipIywVMpYomSxyXpT3Swfw9KdFBXKaNRUVIUJWUSeUpukbTvUwp5ShJZJTxtU1KSQEVJUZSUGagSHjt8l26PZODIdufvUEUHDd9lNCpKiqKkTDDRIVpKODhile6Hf2Ttu2BShqaEZzYqSoqipEwoJTxW9p0r/dl3MY9D1/hdRqOipChKyoQ8JXd0UcpyCf3+NHtKdo6RiQ5pnpaSABUlRVFSxpfAU/K4XfiCypUmzED+HTBw+KCG7zIbFSVFUVImEKfMEECWW+hPd/guItFhoPadilImo6KkKErK+Pzxs++y3C76fWn2lAbVvguWGUrXjJRkSEqURGSViOwTkVoR+XKUz7NF5An7+RYRqQz77H7bvk9EbklkU0SqrI391qY33hgiUioim0SkQ0S+HWYnT0R+KyJ7RWSXiPxr6rdHUZRoJEoJ97gzYJ9SZKKDfdqpp5TZJBQlEXED3wFuBWqAj4lITUS3e4BWY8x84GHgIXttDbAGWASsAr4rIu4ENh8CHjbGVAOt1nbMMYAe4CvAF6NM/z+MMQuBi4GrROTWRN9XUZTE+OIcXQHgcbnoT7NLEln7zmNVyaeZDhlNMp7SMqDWGFNnjOkD1gGrI/qsBh6zr58CbhDHZ14NrDPG9BpjDgK11l5Um/aaldYG1ubt8cYwxnQaY17BEacQxpguY8wm+7oPeAsYuYPlFWUCEUggSlluSfvDP7L2nTtUvVzjd5lMMqI0Azga9r7etkXtY4zxAW1AaZxrY7WXAqetjcixYo2REBGZBHwAeDHG5/eKyDYR2dbY2JiMSUWZ0PjiHIcOjlfiS/PDP7L2HTiJGekOKyrxSUaUov2vi/xXjdVnuNqTnccgRMQDPA58yxhTF62PMeYRY8xSY8zS8vLyRCYVZcITOnk2xj4ljzv9+5Qia99BZmzqVeKTjCjVA7PC3s8EjsfqY0WgGGiJc22s9iZgkrUROVasMRLxCLDfGPOfSfRVFCUJ/Ak8pSx3BnhKoTJDAzgenIpSJpOMKG0Fqm1WnBcncWF9RJ/1wF329R3ARuP8mrIeWGMz56qAauCNWDbtNZusDazNZxKMERMReQBHvD6XxPdUFCVJ/Imy71zpX1PyR1n3Uk8p8/Ek6mCM8YnIZ4ENgBt41BizS0S+DmwzxqwH1gI/FZFaHO9ljb12l4g8CewGfMB9xhg/QDSbdsgvAeusoGy3tok1hrV1CCgCvCJyO3Az0A78A7AXeMu68N82xvww9dukKEo4/mT2KWVI9l141QlnTUkTHTKZhKIEYIx5Dnguou2rYa97gI/EuPZB4MFkbNr2OpzsvMj2eGNUxph69J8YRVHOiZCnFLPMUPoTCoL7kcJ1Uz2lzEcrOiiKkjL+gEHEOTcpGh6XK+3hu2gbfDMhrKjER0VJUZSU8QdMTC8JbO27NIfvgh7RWdl3GeDBKfFRUVIUJWV8ARPz2ArIjPBdMA3qbE9Js+8yHRUlRVFSpt8fIMsd+/GRCWWGgp6SK2LzrFZ0yGxUlBRFSZlEouT1ZM6akiti82y656XER0VJUZSU8flNzLOUIDNSr6OJkset2XeZjoqSEpOTbT387PXD6Z6GkoH0+0388J3bRb/fpPWU10CUNSW3rillPEntU1ImJnf/eCu7T7RzU80UphTlpHs6SgbhCwTiJjpkuYIH6sVPiBhJYq8pqShlMuopKTFp7eoD0B9iZRAJw3fWi0qnVxIK30WUGUp3WFGJj4qSoigpkyjRIct6R+nMwIu6pqSeUsajoqQoSsokTgl3hCCdmW5Bh8gdmX1nRckYw7HT3emYmhIHFSVFUVIm8eZZ59HSn8ZQmT90ntJAW3iZoWffOcFV/7qRNw+3pmN6SgxUlJSEaLBDiaTfHyDLlTh8l05PyUSpfReefbdpXwMABxo6Rn9ySkxUlBRFSRmfP4GnZAUrnaIUXM4KX1PKcg9UdMj2uIH0enPKYFSUlITo+R9KJP0BEwrRRSMoWOl84Mc6uiLoKXnC0taVzEFFSUmI/sgqkfj8gdBepGh4g2tKacy+M1FSwsOz74JhvT6fekqZhIqSoigpkyh85/VYUfKlM3wXrfbdQE2+oKfU0+8f/ckpMVFRUhKi4TslkmQKsgL0+tL3wA+VGYqxTyn4eVefilImoaKkJETDd0ok/YH4ohRMIuhNY2gsuKYkYdMMP+Svz++IUbd6ShmFipKiKCmTqMxQtvWU0rleEzoOfZCn5MwpGFrU8F1mkZQoicgqEdknIrUi8uUon2eLyBP28y0iUhn22f22fZ+I3JLIpohUWRv7rU1vvDFEpFRENolIh4h8O2Jel4rIu/aab4nEOb9ZiYneNCWSfn/87LtMCN9FSwkPz77rsx16+jXRIZNIKEoi4ga+A9wK1AAfE5GaiG73AK3GmPnAw8BD9toaYA2wCFgFfFdE3AlsPgQ8bIypBlqt7ZhjAD3AV4AvRpn+94B7gWr7Z1Wi76sMRsN3SiS+QCC0QTYa2SFRSr+nFL7HN7yiQ1CUunVNKaNIxlNaBtQaY+qMMX3AOmB1RJ/VwGP29VPADdYrWQ2sM8b0GmMOArXWXlSb9pqV1gbW5u3xxjDGdBpjXsERpxAiMg0oMsZsNk5u6E/CbClJoB6SEgsnfJeMp5RGUYqSfedxu0JVwoOhRV1TyiySEaUZwNGw9/W2LWofY4wPaANK41wbq70UOG1tRI4Va4x4865PMG8AROReEdkmItsaGxvjmJxYqIekxMLJvovnKWVCooPzd/iaktcePhgImJAo6ZpSZpGMKEX7nxf5vIrVZ7jak51HMnMa3GjMI8aYpcaYpeXl5XFMTkzUY1IiSZQSnp1lPaU0PvCjFWQNenB9/kBoY6+KUmaRjCjVA7PC3s8EjsfqIyIeoBhoiXNtrPYmYJK1ETlWrDHizXtmgnkrSaAekxJOIGAIGOJvnnUPPPzThTEGl0B4flN2mCgNeEqa6JBJJCNKW4FqmxXnxUlcWB/RZz1wl319B7DRruOsB9bYzLkqnGSDN2LZtNdssjawNp9JMEZUjDEngDMicrldq/qzMFuKogyRYD27+PuUgp5SGo+uCJiz1pNgYM79vgFPSdeUMgtPog7GGJ+IfBbYALiBR40xu0Tk68A2Y8x6YC3wUxGpxfFe1thrd4nIk8BuwAfcZ4zxA0SzaYf8ErBORB4AtlvbxBrD2joEFAFeEbkduNkYsxv4DPBjIBf4nf2jpIiG75Rw+iPK9ERDRPC6XWlfU3JFzPHs8J3zPVSUMouEogRgjHkOeC6i7athr3uAj8S49kHgwWRs2vY6nOy8yPZ4Y1TGaN8GLI72maIoQyMY9gp6Q7HI9rjSvnk2UjdDYUVfIFRuSNeUMgut6KAkRNeUlHBCopTljtsvO8uV3tp3AXNW5h2EeUq+QCgMqaKUWagoKQmJs3SnTECCQuONs6YU/Dyd4Tu/ib2m1OcPhDbR9vsNvlFKyGjr6h+VccYyKkqKoqREb8hTShC+y3KnNXxnzNnp4HB2Tb5wIeoZhXn+7t0TXPj137OlrnnExxrLqCgpCVFHSQknKDTJeUrpC435olQyDw/f+cJOnB2NEN4f9jQA8OoBFaV4qCgpMVExUqIRFJrk1pTSmxLudsVICfcbfAFDjvX2RqP+3fHT3QAcbOoc8bHGMipKiqKkRG+SnlK6s++iHa8xkBLup98foCA7CxgdT6m9x1lPOtnWPeJjjWVUlJSYBOPx6jEp4SS7puT1ZICnFFF1Ijwl3Oc3FOU4u2JGo6pDW7cjSsdP9yToObFRUVJiomKkRCPZNaVsjzut6da+wOBK5uHVy/0BQ4EVpdHYQNtuRelUe49mtMZBRUlJiNGdSkoYQe8nJ4GnlOt1p7Vagi8QGLSm5A1bU+oPBCjIDnpKIzvPQMBwptdHvteNL2Bo7/YlvmiCoqKkKEpKDHhK8RMd8rLcaT1AL96aUk+/H2OgcJQ8pTO9PoyBqvJ8AJo7e0d0vLGMipKSEI00KOEMZN/Ff3zked109qbPI/AHzKBK5kFR6upz5jVaiQ7B0F1VWQEALZ19IzreWEZFSUmIapISTrK173K9njSH7wzuGGtKXdaDK8wZnfBdMMmhqjQPgGYVpZioKCmKkhKhlPAEopTvdTtrN2k6U8kfGBy+C56WGylKIx1mDHlKNnynnlJsVJSUhGimkBJOstl3uV5nzakrTetKsRIdROBMTzB8Zz2lEU5db4sI3zV36JpSLFSUFEVJiV6fH7dL8CQQpTyv88APrt+MNtESHUSE3Cw3HXatKz97lDwlu3G2rMBLQbZHw3dxUFFSEqJ+khJOny+QcD0JnEQHSKenZKIKZ57XzRkrEl63i2yPi54RrtEX9JSKc7Moyfdq+C4OKkpKQjR6p4TT6wskXE+CAVFKV1p4tDUlcMKKwTUej1vI9brpGfE1JR8ugXyvR0UpASpKiqKkRE+/P0lPKRi+S5+nFLmmBJCX5aHdril53C7ystx0jvAc27r7KcrNwuUSygq8NHWoKMVCRUlJAnWVlAG6+vwhwYlHMNGhM01rSv5AILGn5BKKcrNC4byRor2nn6IcZ09UaX62JjrEQUVJiYmWF1Ki0dPvJzfBsRWQ/vCdzx/DU/K6Q4kHHpdQlJMVWvMZKdq6+ynOdUSpvDCb5s4+AgH9+YpGUqIkIqtEZJ+I1IrIl6N8ni0iT9jPt4hIZdhn99v2fSJySyKbIlJlbey3Nr3nMMbnRWSXiOwUkcdFJCe126OArikpZ+N4SolFKT8DwnfRPKU8rztUFTw7y01RbhZtI1yLzgnfOfejrMCLP2Bo7dIQXjQSipKIuIHvALcCNcDHRKQmots9QKsxZj7wMPCQvbYGWAMsAlYB3xURdwKbDwEPG2OqgVZreyhjzAD+BlhqjFkMuG0/JUkE5wdaNUkJp6vPHwrNxWNgn1K6wnfRs+9yw0KP2R4XRbmeUDhvpGgP85TKCrMBdF0pBsl4SsuAWmNMnTGmD1gHrI7osxp4zL5+CrhBRMS2rzPG9BpjDgK11l5Um/aaldYG1ubtQxwDwAPkiogHyAOOJ/F9FYuG75RoJBu+y8+2a0q96ds8G9VTCpt7tsdFUU7WiItSW7cvtKZUVhAUJV1XikYyojQDOBr2vt62Re1jjPEBbUBpnGtjtZcCp62NyLFSGsMYcwz4D+AIcAJoM8b8PtoXFJF7RWSbiGxrbGyMeSMmKhq+U8JJNnyXm+XG7RI6ekf2gR+LaMehA2d5edkeN8W5WZzp9eEfwTWe9p4wT0lFKS7JiNLgf9XBEZ1YfYarPeUxRGQyjhdVBUwH8kXkzih9McY8YoxZaoxZWl5eHq2LoiiWZMN3IkJRjidtZwfFWlM6S5SyXBRZsRipDLyefj99vkBonHIrSo1nVJSikYwo1QOzwt7PZHAYLNTHhsqKgZY418ZqbwImWRuRY6U6xo3AQWNMozGmH3gauDKJ76tEoGE8JRwnfJc4JRygKDcrlOk22vT7AoOqhINTKDZItscV8mBGSjyDmX1BUSrK9eB1u3RNKQbJiNJWoNpmxXlxkgXWR/RZD9xlX98BbDROFc/1wBqbOVcFVANvxLJpr9lkbWBtPjPEMY4Al4tInl17ugHYk9xtUcLR8J0SxBhDV58vqfAdMCrrNbHo95uolSeK87yh19keN0W2Uvjp7pERiaAoTbKiJCKUFng1fBeDhL/uGGN8IvJZYANOBtujxphdIvJ1YJsxZj2wFvipiNTieC9r7LW7RORJYDfgA+4zxvgBotm0Q34JWCciDwDbrW2GMMYWEXkKeMu2bwceGeqNUhTFKTEUMCQVvgPHKxjpPUDRMMbQ549eDqkkXJSyXGHZcCMjEuF174KUFWSrKMUgKR/cGPMc8FxE21fDXvcAH4lx7YPAg8nYtO11DGTPhbcPZYyvAV+Ldo2SPOopKUGCG2GTyb4Dx1M61T76D98+f+yDCCfnD4hDvtdDReHIrvG0dUUTJS8NuqYUFa3ooMRExUiJJHiSbLLhu+Lc9ITv4p35VJI/4Cm5XRLKhmsYIfE8HQzf5Q2IUkVhTlrEeiygoqQkRBMdlCDB6gzJh+/Sk+jQF+d03PDwHUBOlpMWPlKeS7Tw3fRJuTR19I74MexjERUlJSHqMSlBgtUZkinIClCU46GnP0DvCJ9XFEkwfBdNlIKeUfAodHDq0Y1Y+M6KUmHOgCjNmJwLwIm2nhEZcyyT3P8sRVEUBo4RD3+gx2NgD5CP7ILkvKvhIF74zuUSfvGXy88K41UUZtNwZmQEoq2rj6Icz1kbeWdMckTp+OluqsryR2TcsYp6SoqiJE1wg2nSomS9g9HOwIsXvgO4cl4ZC6cWhd5PLcrh5Ah5LW3d/RSHrScBzLSe0rHW7hEZcyyjoqQoStIED8cryslK0NNhsvVGRvuk1d4EohTJ7NI8TrT3jMgaT2tXP5Mj1rGmFucgAvWnVZQiUVFSEqJrSkqQjhTDd2UFzsN4tA+164+zphSNOaV5GAP1rV3DPpfGM72h0kJBstwuphTmqKcUBRUlRVGSJrimVJCdnCiF6ryNckmdYPguO8qaUjTmlDrrOoebh1+UGs70UlGUPah95uTcERHBsY6KkpIQTQlXgpzp6SfP6456TlE0guG70faU4mXfRaPSitKhYRYlf8DQ0jnYUwKYW57PgcbOYR1vPKCipCREw3dKkDM9vqS9JHDCVJPzska9pE6iRIdIJudlUZTj4UBjx7DOo7mzl4BxUs4jmVdeQFNHb6jig+KgoqQoStKc6e1Pej0pSGlBNk1n0hO+S1aURISa6UXsOt6e8ljGGL74329z5w+30NF7dqXxYJWI8sKcQdfNrygAoHaYhXCso6KkJEQdJSXImR7fWZtAk6GswEtz5+h6Sj12s26OJ/m9UYunF7P3RDs+G/pLljcPt/LUm/W8UtvE2j8ePOuzoy1OOHBWSe6g6+aVO6J0oEFFKRwVJSUmKkZKJO09vpQ9Jaci9uh6SsEj2JOt0QewaEYRvb5Ayus82w63AnDpnMn89PVDZ1WvCK5RBRMpwplVkofX41JPKQIVJSUhRheVFEt7d/9ZNdySoaLQ2Zg6mv+PulOs0QdwwYxJAGw/0prSWLUNHZQXZvM3N1TT1NHH7949GfrscHMnZQXeqOtwbpcwr7yAPSdSDxmOZ1SUlJgEi6KoJClBmjt6Kc33Ju4YxozJuXT3+2kdxQX9YOHYZGv0Acwrz6e8MJvXDjSnNNb+hg6qKwq4Zn4ZVWX5/GTzodBne06eCYXporFkRjHvHmvTX/zCUFFSYqI/Jko4/f4A7T0+SvIHZ5LFI1jnbTQ3inb1+/B6XGfVm0uEiHDlvFJeO9CctEgYYzjQ0MH8igJcLuHOy+fw1pHT7DzWRq/Pz57j7Vw0e1LM65fMKuZ0Vz9HW3QTbRAVJSUh+kucAtDa5awLleSnFr4L1Xk7PXobRbv7/CmtJwW5an4ZTR297E4ypHaqvZeOXh/VNpPujktnkpvl5iebD7H5QDN9/gCXzSmJef0SGzJ859jplOc6XlFRUhQlKVo7nfBbqp5SUJTqR9NT6vOTl+TpuOHcsLACt0v47Tsnkuq/v+EMAPOsKBXnZnHHpTP55VvH+OozuyjOzeLq6rKY1583tRCv28U79W0pz3W8oqKkJIG6SgqhtO7JKXpKxblZ5HvdHBvF4qNdfb6UkhyClBZkc9X8Mn7zzvGkQni1Np27uqIw1PZ3q87jghnFnGjr5msfqCEnjjh6PS6WzCxmy8GWhGP9YfcpNu49lcS3GNuoKCkJ0fCdAgOeUmmKnpKIMHNyXmjPzmjQ1edPKckhnA9eOJ2jLd1srkuc8LC/oYPi3KxQ4VlwDvP71V9dyc5/voUPXTIzoY0r55Xybv3puCf0tnb28Rc/2cbdP94WOmhxvJKUKInIKhHZJyK1IvLlKJ9ni8gT9vMtIlIZ9tn9tn2fiNySyKaIVFkb+61N7zmMMUlEnhKRvSKyR0SuSO32KIoSpGWInhI41Qv2j+Im0a4+/5A8JYDblkyjJN/Lo68cSti31mbeiZydUCEiZCe5cfeKeWUEDLxRF9tbert+YM1p66HUUtbHGglFSUTcwHeAWx/S3TUAACAASURBVIEa4GMiUhPR7R6g1RgzH3gYeMheWwOsARYBq4Dviog7gc2HgIeNMdVAq7Wd8hj2mm8CzxtjFgIXAnuSvTHKAOooKQBNHX2IMOhsoGSonlLAkZauETmvKBrt3f1Jn/kUSU6Wm08sn82Le09Ra9eMYlFrM+/OhYtnTyLb4+LVA00x+4R7me/Wj++kiGQ8pWVArTGmzhjTB6wDVkf0WQ08Zl8/Bdwgzq8Oq4F1xpheY8xBoNbai2rTXrPS2sDavH0oY4hIEXAtsBbAGNNnjBnf/5rDjIbtlHBOtfdQVpBNVpIVwsOprijEmIE1mJGmvbufSXlDEyWAT11ZSb7Xw0PP74vZp6mjl5bOPhZMKYzZJxlystwsn1vKS/saY65jHW7uItvjorI0b9wnRSTzv2sGcDTsfb1ti9rHGOMD2oDSONfGai8FTlsbkWOlOsZcoBH4kYhsF5EfisjgWh+AiNwrIttEZFtjY2PsOzFBUXFSAE609TCteHBh0WRYMMXxJvYn8DyGi9NDqDwRTmlBNp9ZMY8Xdp9ic4zNtO+ddL7LeVPPTZQAbqqZwsGmzpiifaSli9kleSyaXsyek+O7AkQyohRt91nkYypWn+FqH8oYHuAS4HvGmIuBTmDQehiAMeYRY8xSY8zS8vLyaF0mJMEwue42VwBOtvUwpWhoolRZlo/X7WLPiZEXpX5/gK4+/zmJEsDdV1UxuySPLz/9TtTkgn2nnO9yrp4SwM01UwDYsOtk1M+PtHQxpzSP86cVcrSlO25SxFgnGVGqB2aFvZ8JHI/VR0Q8QDHQEufaWO1NwCRrI3KsoYxRb4zZYtufwhEpJUlUi5RwTrYP3VPKcrtYPKOItw6P/CJ9W7fzwD6X8B04dfP+/Y4lHG7u4oHfDl6O3nH0NBWF2Wdl3g2VKUU5XDRrEht2DU75NsZwpKWLWSV51EwvAmDvKIh7ukhGlLYC1TYrzouTVLA+os964C77+g5go3F+vV4PrLGZc1VANfBGLJv2mk3WBtbmM0MZwxhzEjgqIufZa24AdifxfZUIVJuUrj4fbd39TB2iKAFcMnsy7x5rC511NFIERelcPSWA5XNL+fS1c/nFliM8sfVIqN0Yw5a6FpZVlQzKvBsqty6eyrvH2qiLqBre3NlHV5+fOSV5nD/NEaXxXMQ1oSjZ9ZvPAhtwsteeNMbsEpGvi8gHbbe1QKmI1AJfwIbJjDG7gCdxxOB54D5jjD+WTWvrS8AXrK1SazvlMew1fw38XETeAS4C/r9Ub5CiKE7oDmDqEMN3AJfMmUyvLzDiD9TWTqcc0qQhZAlG4//cch7XVJfxj7/eyYt7HE9mx9HTnGzv4drq4Qv3337xDFwCT7917Kz2I6EzmfKYWpTDpLyscS1KSe0uM8Y8BzwX0fbVsNc9wEdiXPsg8GAyNm17HU52XmT7UMbYASyNdo2SPBrGU4IPxpmT84ZsY2nlZABePdDEhbNiFyk9V07Z016nFKW2yTcWHreLb3/sEj756BY+/dM3ue/6+Ww+0ExBtodVF0wdljHACeFdU13O02/V84WbFuCyxWSPhM5kynNOyJ1WlHRtvrGIVnRQEmI0gDfhOdTkHHxXWTZ0UaoozOGCGcVs3NMwXNOKysn2c/fqIinOy+Lnf7Gcm2qm8M0X97PtcAv/9MFFQ94LFYsPXzqT4209Zx2fcbi5C5GBXwjOn1bEvpNnUj4hd6wwtDociqJMKA41d5HvdVNecG7ex/ULK/j2xv20dPZRkuK5TMnS0N6D1+MaljWlcApzsvjenZdyuLkTr8fFtOLBR5yfKzfXTGFSXhY/2XwoVMj1SEsXU4tyQjX0zp/mnJB7qLmT+RXnnvmXaainpCRGHaUJz8GmTirL8s95Uf/mmikEDPz2ncgE3uHjZHsPU4tyhi0BIZI5pfkjIkjgbKS9c/kcXthzKuSd1jZ2UFU2sMWyxiY77Do+PkN4KkqKoiTkULMjSufK4hnFLJpexLqtRxN3HiKHm7uYVTIyojEa/NkVc8hyuVj7ykH6/U5iyOIZxaHP51cUkOWWUdnzlQ5UlJSEqKM0senu83O0pSvusd6psOayWew63s7WQ4mPa0iV4EmwwzXXdFBRlMOHL53J428cYd3Wo/T5Alwclhji9biYV14wbjPwVJSUhGj23cRm78l2AgYW2Y2b58odl86irCCbb/z+vWGxF07jmV7O9PrGtCgBfPHmBRTkePjKr3dSmO3huvPOTj2vmV6koqQoysQkmH4cXMs4V3K9bu67fh6b65p57t3kTnhNlnePOcVKFw5DPbp0UlqQzU/uXsb7L5jGtz528aCzoWqmFdFwppemjt40zXDkUFFSEqIp4ROb3cfbKcrxhI41Hw4+efkcLphRzD/+eicn2obvRNpth1vJcsuI7oMaLZbMnMR3PnEJ1y+sGPTZeK7soKKkxEHFSHEOmFs0vXhYs9k8bhff+NML6fMF+PMfbeV0V9+w2H35vUaWzJwU9wjy8cDi6cWIwPYj4+80HhUlJSG6pjRxae/pZ/fxdpZVlQy77eophXz3E5dQ19jJh7732jmftVTbcIZdx9u5dfHwVVnIVIrzslg4tYgtBxMf2T7WUFFS4uD8ZqyaNHF581ArAQPLR0CUAK5dUM5P71lGS2cf7/vWH/nGC+8N2Wv6r4215GS5WH1R5HFv45PlVSW8ebh1xAvcjjYqSkocVI4mOq/XNZPlFi6ePXnExlg+t5Tff/5abqqZwrde3M+V/7qRzz+xg+d3ngwVV42HMYYfv3qQZ3Yc5y+vmUt54fDUvMt0Lp9bQk9/gHePja8QnpYZUhKih/xNXF7Yc4rlVaXkekd2jaaiMIfvfPwS/nplOz965RDP7zrJr7Y71bIrS/OYX1HI7JI8pk/KoSDbQ67XTU+/nxNtPWza28Db9W3csLCCv7mhekTnmUksqyoF4PW6Fi6dMzKebDpQUVIUJSq1DR3UNXbyqSsrR23MhVOLeOiOJTzwJ4t583Arbx1p5e2jpznc3MVrB5ro6vMPuqZmWhEP3L6Yjy2bjds1MqWFMpGSfC8LphTwel0z910/P93TGTZUlJSYBKyDpH7SxOR3dg/RTfao7tEky+3i8rmlXD63NNRmjKG9x0dXn4/OXj85WS5K8r2D9vBMJK6eX87Ptxymp98/bjIOdU1JiUkobKeqNOEIBAxPbDvKFXNLR6z4aKqICMW5WUwrzmV+RQEzJ+dNaEECuO68cnp9AV6vGz9ZeCpKSkxUiyYuf6xtor61m48tn53uqShxWF5VQk6Wi/95rzHdUxk2VJSUmAw4SipPE43vv3SAsoJsblk0+qE7JXlystxcPreU/9mnoqRMADTrbmKypa6ZzXXNfGbFPLI942OdYjxz3YJy6po6Q8emj3VUlJSYhDwl1aYJg88f4F9+u5uKwmw+oaG7McF1C5wK4v+zf3x4S0mJkoisEpF9IlIrIl+O8nm2iDxhP98iIpVhn91v2/eJyC2JbIpIlbWx39r0DnUM+5lbRLaLyLPJ3xYFBtaUVJQmDj9+7RA7j7XztQ8sGjfZXOOdqrJ8ZpXk8j/7GtI9lWEhoSiJiBv4DnArUAN8TERqIrrdA7QaY+YDDwMP2WtrgDXAImAV8F0rEvFsPgQ8bIypBlqt7ZTHCJvb3wJ7krsdSjgavptYvFN/mn97fh83LKzgfReM//px4wUR4frzKni1tple3+B9XGONZDylZUCtMabOGNMHrANWR/RZDTxmXz8F3CBOSeHVwDpjTK8x5iBQa+1FtWmvWWltYG3ePsQxEJGZwPuBHyZ3O5RwdJ/SxKGhvYfP/Owtyguz+fePXDisFcGVkWfFeeV09/t54+Dwn+Y72iQjSjOAo2Hv621b1D7GGB/QBpTGuTZWeylw2tqIHCvVMQD+E/g7IG7FQhG5V0S2ici2xsbxEZcdDjTrbmLQ0tnHnWu30NrVx/fuvISSfG+6p6SkyBVzy/B6XGzaO/afX8mIUrRfmSKfVrH6DFd7ymOIyG1AgzHmzSifn93ZmEeMMUuNMUvLy8sTdZ8wDCQ6qDiNV+pbu1jzyGYON3fxw7uWsmTm2D8cbyKS63VzxdxSXnpv7K8rJSNK9cCssPczgeOx+oiIBygGWuJcG6u9CZhkbUSOleoYVwEfFJFDOOHBlSLysyS+r2IxEX8r44s3D7fyJ999jRNtPfzoU5dx5byydE9JOQeuP6+cusZODjd3pnsq50QyorQVqLZZcV6cpIL1EX3WA3fZ13cAG43z6/V6YI3NnKsCqoE3Ytm012yyNrA2nxnKGMaY+40xM40xldb+RmPMnUneFwVUjcYp/oDhWy/u509/sJmcLBdPf+ZKrpyvgjTWWXGec2z6S2N8I23CwlHGGJ+IfBbYALiBR40xu0Tk68A2Y8x6YC3wUxGpxfFe1thrd4nIk8BuwAfcZ4zxA0SzaYf8ErBORB4AtlvbDGUM5dwI2LCdRu/GD+/Wt/GPz+zk7aOnWX3RdP7l9sUU5WSle1rKMFBZlk9VWT6b9jVw1yhWdh9ukqpmaIx5Dnguou2rYa97gI/EuPZB4MFkbNr2Omz2XER7ymOEff4S8FKsz5XoqBaNH1o6+3j4hff42ZbDlOZn8801F02YE1onEivOK+cXW46M6arhE7vErhKXgQQHlaexSlt3P2v/WMfaVw7S3e/nU1dW8vmbFqh3NE65/rwKfvTqITbXNXO9DeeNNVSUlJhoRYexy+muPn6y+TA//GMd7T0+3n/BND53YzXVUwrTPTVlBFlWVUJulpuX9jaoKCnjDxWjscfh5k7WvnKQ/95WT3e/nxsWVvCFmxewaHpxuqemjAI5WW6unFfKpn2N/JMxY3ITtIqSkhDVpszGGMO2w62s/eNBNuw+icclrL5oBvdcXcX504rSPT1llFmxsIIX9zZQ19TJvPKCdE8nZVSUFGWM0tbVz9Pb6/nFliPsb+igODeLv1oxj7uuqKSiKCfd01PSxApbNfylfY0qSsr4RMN4mYMxhreOtPLzLUf47Tsn6PUFuHDWJP7tw0u47cJpE/54cAVmleRRXVHAS/sauOfqqnRPJ2X0f7CSEK2Bl34az/Sy/u3jPLn1KPtOnaEg28Mdl87k48tn63qRMojrF1bw41cP0dnrIz97bD3mx9ZsFWUC0dPv58U9DfzyrXr+571G/AHDkpnF/N8PXcAHL5w+5h42yuixYkE5j7xcx2sHmrmpZmwdaa//q5WEaPhu9AiG55568xjPvnOcMz0+phbl8JfXzOVDl8xggaZ0K0mwtLKEfK+bl/Y1qCgpipI6R5q7+NX2Yzy9vZ7DzV3kZrlZtXgqH7pkBlfOK8PtGnupvUr68HpcXF1dxkv7GjFjLDVcRUlJiDpKI8PJth6efec4v3nnBG8fPY0IXDG3lL9eWc2qxVMp0PCccg5cf14FG3adYn9Dx5jysPV/vZIQPU9p+Gju6OW5nSf5zdvH2XqoBWNg8Ywi7r91IbddOJ0Zk3LTPUVlnHDdeU5q+Ka9DSpKiqIM0Nbdz4ZdjhC9dqAZf8Awv6KAz9+4gNuWTGPuGNxLomQ+04pzWTi1kE37Gvj0dfPSPZ2kUVFSlBGgo9fHi3tO8Zu3T/Dye430+QPMLsnjf103lw9cOJ3zphSOqTi/Mja5bkE5j756kO4+P7nesVE1XEVJUYaJtq5+Xthziud3nuDl/U30+QJMLcrhz66YwwcunM6SmcUqRMqocuX8Mn7wch3bDrdwTXV5uqeTFCpKSlTC15F0SSk2TR29/H7XKX638wSbDzTjCximF+fwieWzuXXxNJbOmYxLM+eUNHFZ5WQ8LuG1A80qSsrYxh8IEyXNvzuLk209bNh1kt/tPMEbB1sIGJhTmsc911Rx6+JpXKgekZIh5Hk9XDx7Eq8daE73VJJGRUmJii+gQhTO0ZYunt/pCNFbR04DUF1RwGevn8+qxdM4f5quESmZyRXzyvj2xv209/SPicMdVZSUqPT7A6HXEzF85w8Y3q4/zaa9Dby4p4HdJ9oBWDS9iC/evIBVi6cxv0Kz5pTM58p5pXzrxf1sqWsZE9UdVJTGOZ9bt51rqsv58KUzU7qu3z/xlOhMTz9/3N/Ei3saeGlfA82dfbgEls4p4f5bF3Lr4mnMLs1L9zQVJSUunj2JbI+L1w40jR9REpFVwDcBN/BDY8y/RnyeDfwEuBRoBj5qjDlkP7sfuAfwA39jjNkQz6aIVAHrgBLgLeCTxpi+VMcQkVm2/1QgADxijPlmqjdorPPrHcf59Y7jKYtSd78/9Ho8e0p1jR1s3NvAxr0NvHGwBV/AUJybxYrzylm5sILrFpQzKc+b7mkqypDJ9ri5rLKEzWNkXSmhKImIG/gOcBNQD2wVkfXGmN1h3e4BWo0x80VkDfAQ8FERqQHWAIuA6cAfRGSBvSaWzYeAh40x60Tk+9b294Ywhg/438aYt0SkEHhTRF6ImPe4xhcWgkuV7j5/4k5jkD5fgG2HWnjRCtHBpk4AFkwp4C+umcvKhRVcMnsSHrcrzTNVlOHjinml/PuGfTR19FJWkJ3u6cQlGU9pGVBrjKkDEJF1wGog/OG+Gvgn+/op4NvirPquBtYZY3qBgyJSa+0RzaaI7AFWAh+3fR6zdr+X6hjGmM3ACQBjzBlre0bEvMc1necgLD3hntJwTCaNNHX08tK+RjbuPcXL7zXR0evD63ZxxbxSPnVlJSsXVjCrRMNyyvjlynmlALxe18xtS6aneTbxSUaUZgBHw97XA8tj9THG+ESkDSi17a9HXDvDvo5msxQ4bYzxRek/lDEAEJFK4GJgS7QvKCL3AvcCzJ49O1qXMUlnry9xpxh09YWH78aWLBlj2H2inY17Gti4r4EdR09jDFQUZnPbkmmsXFjBVfPL9DwiZcJwwYxiCrI9vHZgfIhStDzXyKdUrD6x2qPFRuL1H8oYzkUiBcAvgc8ZY9qj9MUY8wjwCMDSpUvH1hM4Dl19Qxel8DWlsUB3n59Xa5vYuK+BjXsaONneA8CFM4v53A0LuOH8CmqmFelGVmVC4nG7uHTOZLYebEn3VBKSjCjVA7PC3s8EjsfoUy8iHqAYaElwbbT2JmCSiHistxTeP+UxRCQLR5B+box5OonvOq7o6B26sHSFeVmZqtLHTnc7SQp7TvHagWZ6fQHyvW6uqS5n5fkVrDivnIrCnHRPU1EygmVVJfz7hn20dPZRkp+5yTvJiNJWoNpmxR3DSSr4eESf9cBdwGbgDmCjMcaIyHrgFyLyDZwkhGrgDRzvZpBNe80ma2OdtfnMUMaw601rgT3GmG+kemPGA13nEL5r6eobxpkMD/6AYcfRVl7c4yQp7D15BoDZJXl8fPlsVi6sYFlVCdmesVF4UlFGk2VVJQBsPdTCLYumpnk2sUkoSnb95rPABpz07UeNMbtE5OvANmPMepyH/09tkkELjshg+z2Jk1zgA+4zxvgBotm0Q34JWCciDwDbrW1SHUNErgY+CbwrIjusjb83xjw3tFs19uiwouT1pJ5J1toZJkppdJXauvt5+b1GNu519g61dvXjdgmXVU7mH953PtcvrGBeeb5WU1CUBCyZWYzX42LrwTEuSgD2Qf5cRNtXw173AB+Jce2DwIPJ2LTtdQxk6IW3pzSGMeYVoq83TRiCyQrZQxClls7+0OvRrH1njOFAYycb957ixT0NbDvcij9gmJyXxfXnVXD9wgquXVBOcW7ml0tRlEwi2+PmolmTeONQZq8rafrROKa9xxGWnKzUw1kn2rrJyXLR0z/0vU7J0uvz88bBltAm1sPNXQAsnFrIp6+dyw3nV3DRrMm4NUlBUc6J5VUlfPelA3T0+ijI0OzTzJyVMiw0nekFoHAI//kONnUyt6yA3SfaR6SiQ+OZXjbZTLk/7m+ks89PtsfFlfNKQ5tY9WhwRRleLqsswR+o5a3DrVy7IDOPslBRGsc0djiiFEhRVfp8AQ42dXJTzZRQIdJzxRjDruPtNknhFG/XtwEwtSiH1RfP4IaFFVw5r2zMnI6pKGORS+ZMxiVOsoOKkjLq1Ld2A6kXV32n/jS9vgCXVZbw7Dsnhryi1NPvZ3NdM3/Y7awPnWzvQQQumjWJL968gOsXOnuHNElBUUaHgmwPi2cU80YG71dSURrH7LMp075AautCz75zAq/bxeVzndIkqThaLZ19bNzbwB92n+Ll/Y109fnJ87q5prqML5y/gJULKzK+9paijGcuqyzhp68fptfnz8jtEypK45T9p87QYNeUUvGUTrR18+S2o9x6wVQm5SWX4dbW3c/vd53kN++c4NXaJvwBw5SibP7k4hncWDOFK+aWDinZQlGU4WdZVQlrXznIu/VtLK0sSfd0BqGiNA7p6ffz0PN78Xpc3FQzhZffa0zqus5eH3/187cIGMMXbz4vlE8fbU0qEDC8dqCZn285zIt7GujzB5hVksu9187l1sVTuWCGHgmuKJnIZVaIthxsUVFSRpauPh+/2HKEH7xcR+OZXr56Ww0n2rrxJeEp7T7ezuee2E5tQwff/cSlzCrJ47St6tDnGwj/+QOG9W8f47821lLX2MnkvCw+ecUcPnjhdJbMVCFSlEynJN9LdUUBWzN0v5KK0jigrbufx147xI9ePUhrVz9Xzivlvz52MZfPLeXfnt8bd03pQGMHD7/wHs++c4KSfC8/uXs5V1eXAYTizb1WlPafOsPnn9zBzmPtnD+tiIc/eiG3Lp6moTlFGWNcVlXCb3Ycxx8wGbf/T0VpDNN4ppe1rxzkZ68fpqPXxw0LK7hv5XwumT051MfjdtHvNxhjzvJijrZ08a0X9/PLt+rJyXJz3/XzuPeaeRSHrSMFyxP1+QJsqWvmz3+8lZwsN99ccxEfWDJdK24ryhhleVUJv9hyhN3H27lgZnG6p3MWKkpjkENNnax95SBPbDuKzx/gfRdM469WzKdmetGgvllWOHwBQ5ZbaDzTy39t3M/jbxxBRPjzq6r4zIp5UTPi3C7B4xIONXey9pU6pk/K5ed/sZwpRVp5W1HGMsHM2tfrmlWUlKHR6/OzYdcp1r1xhNcONON1u/jwpTP49LXzqCzLj3ldlvV2+v0Bfv76Yf5twz56fQE+etks/mZlNVOL4wtMtsfFr7YfI8/rZu1dS1WQFGUcMKUoh6qyfLYcbOYvr52b7umchYpSBtPr8/NabTPP7zzJht0nOd3Vz8zJuXzx5gX86dJZVCQhEB7rKX3l17v45Vv1rDivnK/eVsPc8oKk5hA8Uv0Ty2czpzS2+CmKMra4fK6zOT7T1pVUlDKMzl4fL+1r5PldJ9m0t4GOXh+F2R5Wnl/BHZfO5Kp5ZSmt5WS5HU/pl2/Vc/dVVXzltvOHlCH351dVpXyNoiiZy+VzS3n8jaPsOdHO4hmZE8JTUcoATnf18Yc9DTy/8yQv72+kzxegNN/LbUumccviqVw5r3TIO6+Dx1Z43S7uf9/ClAXp0U8tpbmjj+laHFVRxhXLqwbWlVSUFBrae9iw+xQbdp5kc10z/oBhenEOn1g+m1WLprK0smRYXOpL50wmyy383w9dEPKaUmHlwinnPAdFUTKPqcU5VJbm8XpdC39xTeasK6kojSLHTnfz/M6T/O7dE7x5pBVjYG55Pp++di6rRqgKQvWUQnZ/fdWQBElRlPHN5XNLee7dzFpXUlEaYbr7/Pxu5wme2HqULbYy78KphXz+xgXcungq1VMKR3wOKkiKokRj+dwS1m3NrHUlFaURorWzjx+9epAfv3aI9h4flaV5fPHmBdy2ZHrcFG5FUZTRIrhf6dXaJhWl8Yo/YPjZ64f59w376Oj1sWrRVD51VSXLq0q0LpyiKBnFtOJcFk0v4ve7T/Hp6+alezoAJBXXEZFVIrJPRGpF5MtRPs8WkSfs51tEpDLss/tt+z4RuSWRTRGpsjb2W5ve4R5jpDjd1cddj77B19bv4uLZk/j956/l+5+8lMvnlqogKYqSkdxcM5W3jrTScKYn3VMBkhAlEXED3wFuBWqAj4lITUS3e4BWY8x84GHgIXttDbAGWASsAr4rIu4ENh8CHjbGVAOt1vZwjzHstHb28ZHvb+aNgy089OEL+Mndy1gwCutFiqIo58LNi6ZgDPzm7RPpngqQnKe0DKg1xtQZY/qAdcDqiD6rgcfs66eAG8RxDVYD64wxvcaYg0CttRfVpr1mpbWBtXn7cI6R3G1JjT5fgE/9eCuHW7r48d2X8dHLZqtnpCjKmGDh1EKWVZbw7Y37OX66O93TSWpNaQZwNOx9PbA8Vh9jjE9E2oBS2/56xLUz7OtoNkuB08YYX5T+wzXGIETkXuBe+7ZDRJqBpmh9E3HVg0O5KmMpY4j3YRyi92IAvRcO4+4+zPjakC8tA+YMxxySEaVov/JHnhoXq0+s9mgeWrz+wznG4EZjHgEeCb4XkW3GmKXR+k4k9D4MoPdiAL0XDnofBrD3onI4bCUTvqsHZoW9nwkcj9VHRDxAMdAS59pY7U3AJGsjcqzhGkNRFEXJUJIRpa1Atc2K8+IkFayP6LMeuMu+vgPYaIwxtn2NzZyrAqqBN2LZtNdssjawNp8ZzjGSuy2KoihKOkgYvrPrN58FNgBu4FFjzC4R+TqwzRizHlgL/FREanG8lzX22l0i8iSwG/AB9xlj/ADRbNohvwSsE5EHgO3WNsM8RiIeSdxlQqD3YQC9FwPovXDQ+zDAsN0LcZwNRVEURUk/WhRNURRFyRhUlBRFUZSMQUUpjNEuS5QORORREWkQkZ1hbSUi8oIt7fSCiEy27SIi37L34x0RuSTsmrts//0icle0sTIZEZklIptEZI+I7BKRv7XtE/Fe5IjIGyLytr0X/2zbh63k11jCVoTZLiLP2vcT9T4cEpF3RWSHiGyzbSP/82GM0T/OupobOADMBbzA20BNuuc1At/zJNTnoQAAAw1JREFUWuASYGdY278BX7avvww8ZF+/D/gdzl6wy4Ettr0EqLN/T7avJ6f7u6V4H6YBl9jXhcB7OOWoJuK9EKDAvs4Cttjv+CSwxrZ/H/iMff1XwPft6zXAE/Z1jf25yQaq7M+TO93fbwj34wvAL4Bn7fuJeh8OAWURbSP+86Ge0gCjVpYonRhjXsbJXgwnvIRTZGmnnxiH13H2kE0DbgFeMMa0GGNagRdw6g6OGYwxJ4wxb9nXZ4A9OJVAJuK9MMaYDvs2y/4xDF/JrzGDiMwE3g/80L4fztJn44ER//lQURogWjmlGTH6jjemGGNOgPOwBipse6x7Mq7ulQ27XIzjIUzIe2FDVjuABpwHxwGSLPkFhJf8Guv34j+BvwMC9n3Spc8YX/cBnF9Mfi8ib4pTig1G4edDz1MaIJlyShONVEs7jTlEpAD4JfA5Y0y7xC6kO67vhXH29l0kIpOAXwHnR+tm/x6X90JEbgMajDFvisiKYHOUruP6PoRxlTHmuIhUAC+IyN44fYftXqinNMBELkt0yrra2L8bbPu4LuEkIlk4gvRzY8zTtnlC3osgxpjTwEs46wLDVfJrrHAV8EEROYQTvl+J4zlNtPsAgDHmuP27AecXlWWMws+HitIAE7ksUXgJp8jSTn9mM2suB9qsy74BuFlEJtvsm5tt25jBxv7XAnuMMd8I+2gi3oty6yEhIrnAjThrbMNV8mtMYIy53xgz0ziFRdfgfK9PMMHuA4CI5ItIYfA1zv/rnYzGz0e6Mzwy6Q9OBsl7OPH0f0j3fEboOz4OnAD6cX6LuQcnDv4isN/+XWL7Cs5BiQeAd4GlYXbuxlnArQX+PN3fawj34WqcMMI7wA77530T9F4swSnp9Y598HzVts/FeZjWAv8NZNv2HPu+1n4+N8zWP9h7tA+4Nd3f7RzuyQoGsu8m3H2w3/lt+2dX8Hk4Gj8fWmZIURRFyRg0fKcoiqJkDCpKiqIoSsagoqQoiqJkDCpKiqIoSsagoqQoiqJkDCpKiqIoSsagoqQoiqJkDP8/XqW/tC349s4AAAAASUVORK5CYII=\n", + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAaUAAAD4CAYAAABMtfkzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAgAElEQVR4nOy9e3zcVZ3//3x/5pLJPWnSe9omJaX3UtpSUApquZWLXFaQqriorOyyqF9dXYHvrrLrF3YtP5VVkWURVBaVclmVikWUq8By6xXaQml6oU3vTdLmPpmZz/v3x+czySSZW9IkM0nO8/EozJzP+bzPO9P085r3Oe/zPqKqGAwGg8GQDViZdsBgMBgMhihGlAwGg8GQNRhRMhgMBkPWYETJYDAYDFmDESWDwWAwZA3eTDuQbZSXl2tlZWWm3TAYsp7QgS10ePLIHz+9W3vLiTryW/bSMeZU/IH8DHnnEOtja0szeSd20F44jUDhmIz6NRJZv379MVUde7J2jCj1oLKyknXr1mXaDYMh6zn8L9PZU3ImZ371kW7tb/zxV5z5+t+z9xP3M3X+ORnyzuHIv05nV9FSzvraat5e/woLfn8p7537HWYtvy6jfo1EROSDgbBjpu8MBkO/sLBBej9CxOMDwLYjQ+1SAsT5r+V+B88avwzxMKJkMBj6hYWCeHq3e5w2jYSG2qVeCEqXKDl+ZY9YGuJhRMlgMPQLJ1KSXu3iCpUdyfzDX1SjmoTlihKaeb8MiTFrSmkQCoWora2lvb09064YUhAIBKioqMDn82XalRGPYKNxIiXxOI+VbBAlAO0RKWmW+GWIjxGlNKitraWwsJDKykokzjdDQ3agqtTV1VFbW0tVVVWm3RnxONN38daUnMeK2tk1fdc5rWim77IaM32XBu3t7ZSVlRlBynJEhLKyMhPRDhGWxk90sDojEnuoXeqFoJ1TjJ2JDpp5vwyJMaKUJkaQhgfm72noSJx9507f2eGhdikOsZGS46uJlLIbI0oGg6FfJBIly41INJJ5URJA3S8qJtFheGBEaQTx4osvctlllwEQDAY5//zzWbhwIY8++mivvl/96lf5y1/+AjiJHLfeeiszZsxg3rx5LF26lKeffhqAf/u3f+u85/jx49x7770D4mswGOTaa6+lurqaM888kz179sTt98c//pGZM2dSXV3Nd7/73c72lStXsmPHjgHxxdA/LGzU6r0snU0RSeyaElGxzAK/DIkxojRC2bhxI6FQiE2bNnHttdd2u1ZfX8/rr7/OueeeC8C3vvUtDh48yJYtW9iyZQu///3vaWpqAgZPlB588EFKS0upqanha1/7GrfcckuvPpFIhJtvvpmnn36abdu28cgjj7Bt2zYAbrrpJu66664B8cXQP7zYcfcpRTfPZsPDP1aUPG6ig9k8m92kJUoiskJEtotIjYjcGud6jog86l5/Q0QqY67d5rZvF5GLUtkUkSrXxg7Xpj/ZGCJSJiIviEiziNyTwP81IrIlvY8k+9izZw+zZs3i+uuvZ8GCBVx99dW0trYCTiQxa9Ysli1bxm9+8xsAjhw5wnXXXcemTZtYuHAhO3fu7GbviSeeYMWKFQC0trby05/+lB//+Mfk5OQAMH78eD75yU9y66230tbWxsKFC/nMZz7Drbfeys6dO1m4cCH/+I//eFI/05NPPsn1118PwNVXX81zzz1Hz1OQ33zzTaqrq5k+fTp+v5+VK1fy5JNPAnDOOefw7LPPEg5nfopoVKKKJQpWnM2zWTR9B8TsUzIVHYYDKVPCxdkJ9xPgAqAWeEtE1qjqtphuNwANqlotIiuBVcC1IjIHWAnMBSYBz4rIqe49iWyuAu5W1dUicp9r+z8TjQG0A98C5rl/evr/V0Bznz6VJPzr77ey7UDjQJkDYM6kIm7/+NykfbZv386DDz7I2WefzRe+8AXuvfdevvSlL/HFL36R559/nurq6s6IaNy4cTzwwAN873vf46mnnupl69VXX+Xqq68GoKamhqlTp1JUVNSr33e/+13uueceNm3aBDjiuGXLls73PTnnnHM6I6xYvve973H++ed3a9u/fz9TpkwBwOv1UlxcTF1dHeXl5XH7AFRUVPDGG28AYFkW1dXVbN68mcWLFyf+4AyDgh0JYwEab02pM/U686IkMWnrYrnTiib7LqtJJ1JaCtSo6i5V7QBWA1f06HMF8JD7+gngPHHSoK4AVqtqUFV3AzWuvbg23XuWuzZwbV6ZbAxVbVHVV3DEqRsiUgD8A3BHGj9nVjNlyhTOPvtsAK677jpeeeUV3nvvPaqqqpgxYwYiwnXXpVdk8uDBg4wde9LFfHvx8ssvs2nTpl5/egoS0Csqgt6Zc6n6jBs3jgMHDgyA54a+EomWEIq7ppRd03fac/rOJDpkNelsnp0M7It5XwucmaiPqoZF5ARQ5ra/3uPeye7reDbLgOOqGo7TP9EYx5L4/v+A7wOtyX5AEbkRuBFg6tSpybqmjGgGi54P7Oj7/qRA5+bmdu7lqa6uZu/evTQ1NVFYWHhSPvYlUqqoqGDfvn1UVFQQDoc5ceIEY8aMidsnSm1tLZMmTep8397eTm5u7kn5bOgfkXAYH8RdU/JkWaQkPfYpqW0ipWwmnUgp3lOv51fYRH0Gqj1dP7ocElkIVKvqbxP16TSier+qLlHVJYMRQQwEe/fu5bXXXgPgkUceYdmyZcyaNYvdu3d3rhk98sgjyUx0Mnv2bGpqagDIy8vjhhtu4Ctf+QodHR2AE0n98pe/BMDn8xEKOd+KCwsL44pOlL5ESpdffjkPPeQEvk888QTLly/vJbBnnHEGO3bsYPfu3XR0dLB69Wouv/zyzuvvv/8+c+dm5kvCaKczCoqzphTdp5QNazdOpOQ85iyvSXQYDqQjSrXAlJj3FUDPOZPOPiLiBYqB+iT3Jmo/BpS4NnqOlWiMRHwIWCwie4BXgFNF5MWkP2kWM3v2bB566CEWLFhAfX09N910E4FAgPvvv59LL72UZcuWMW3atLRsXXrppbz44oud7++44w7Gjh3LnDlzmDdvHldeeWXn9N6NN97IggUL+MxnPkNZWRlnn3028+bNO+lEhxtuuIG6ujqqq6v5wQ9+0JnufeDAAS655BLAWWu65557uOiii5g9ezaf/OQnO0Xo8OHD5ObmMnHixJPyw9A/ItH6cVa8NaXsSXSwYiIlj6noMDxQ1aR/cKb4dgFVgB/YDMzt0edm4D739UrgMff1XLd/jnv/LsCTzCbwOLDSfX0f8PfJxojx4XPAPQl+hkpgS6qfVVVZvHix9mTbtm292oaS3bt369y5cwfU5tlnn60NDQ0DanMo+cEPfqAPPPBA3GuZ/vsaDZw4dkD19iJ99Vd39rq2f/8+1duLdMNj/5YBz7rTenu5vvKTm1RVtb45qHp7kW78xTcy7NXIBFinaTxjU/1JuaakzvrNl4BnXEH5mapuFZHvuE6sAR4EHhaRGpzoZaV771YReQzYBoSBm1WdVcZ4Nt0hbwFWi8gdwEbXNonGcG3tAYoAv4hcCVyo3bMDDT34/ve/z969eykpKcm0K/2ipKSEz372s5l2Y9RiR1Px46WEe7Mn0cHqdnSFEFbLJDpkOWlVCVfVtcDaHm3fjnndDlyT4N47gTvTsem278LJzuvZnmyMyhT+7yFOuvhwobKyki1bBnab1Zln9sxVGV58/vOfz7QLo5qo4EgcUeqcJsuSRIdoSrglEMEya0pZjqnoYDAY+kzEFZx4ZYYkiyondKvoYAk2lllTynKMKBkMhj6j7vSdxEkJ92bR9J2gnckYlgg2YqbvshwjSgaDoc9EOqfv4mTfebMnJdyKPbpCxJm+M5FSVmNEyWAw9JnOdO8403ceK3um7yzRzlJI0ek7yQK/DIkxojSCGIlHV1RWVjJ//nwWLlzIkiVLOtu/8Y1v8Pzzzw+IL4a+07V5Np4oCSH1ZH6aTLvvu+9MdMi0X4akGFEaoYyEoyuivPDCC2zatIl169Z1tn35y1/udr6SYWix3dp38bPv3ISCTGffRUUppiSXImb6LssxojQMGK1HVyRj2rRp1NXVcejQoZPyw9A/kqaEd67dZDpScsUnppK5WVPKftLap2SI4elb4dA7A2tzwny4OPm3/tF4dAU4324vvPBCRIS//du/5cYbb+y8tmjRIl599VU+8YlPJPzcDIODnUSULEsIZ8N+oE5R6qqpaGMhmRZLQ1KMKA0Teh5d8aMf/Yjzzz+/8+iKaPv999+f0tZgHl2RLvGiongVz1999VUmTZrEkSNHuOCCC5g1a1bntKM5uiJz2JHEa0qQLQ9/53cs9swnJ9HBRErZjBGlvpIiohksRuPRFUDnURXjxo3jqquu4s033+wUJXN0RebQ6JqSp3ekBLhrSpkVJbUjCCAxBwxE8JjpuyzHrCkNE0bj0RUtLS2d47W0tPCnP/2JefO6qkW9//773d4bho7ONaU4m2fBefhnOlKKRuOxkZKazbNZjxGlYcJoPLri8OHDLFu2jNNOO42lS5dy6aWXdiZohEIhampquqWJG4aOqChZCSKlbKgxFz32PPbLji0WYiKlrMZM3w0TLMvivvvu69W+YsUK3nvvvV7tH/3oR/noRz8a19Y555zDbbfdxvHjxykpKcHv93PXXXdx11139eq7atUqVq1a1fn+17/+df9/iBgCgQCPP/54r/ZJkyaxdq1Tp3f69Ols3rw57v1PPfUUV199NV6v+RXOBNE1pXi17wAi4sn4w9+2bRzJ7LGmZCKlrMZESqOU6NEVw5VwOMzXv/71TLsxenH3ICWKlJzCp5ndp9R57HmP7DswkVI2Y75mDgPM0RW9ueaauKeYGIYIOypKCbPvPBkv52PHXVMy03fZjomU0qQvGzsNmcP8PQ0NGomuKcUXpbB4sDQ0lC71JuGakpm+y2aMKKVBIBCgrq7OPPCyHFWlrq6OQCCQaVdGPBE3JTyhKOHDsjMrSrYdr6JD5rMCDckx03dpUFFRQW1tLUePHs20K4YUBAIBKioqMu3GiCcaKXkSJJrY4kEyXPtO40zTRcSDL9YvOxL3SHdD5jCilAY+n4+qqqpMu2EwZA12qpRw8eLNcKJDV0HWLh8jeLCikdL+9fDT5XDDszDljAw4aIiHmb4zGAx9JrpPyZMwJdyLleFIqbM+X8yebFu8WFGx3Po75/+7XxpizwzJSEuURGSFiGwXkRoRuTXO9RwRedS9/oaIVMZcu81t3y4iF6WyKSJVro0drk1/sjFEpExEXhCRZhG5J8ZOnoj8QUTeE5GtImLOOTAYBojoIX+We/R5TyLiw5PhRIeuig4xkVKsKJlpu6wkpSiJU0fkJ8DFwBzgUyIyp0e3G4AGVa0G7gZWuffOAVYCc4EVwL0i4klhcxVwt6rOABpc2wnHANqBbwHfiOP+91R1FnA6cLaIXJzq5zUYDKlRNwryJNqnJJ6uh3+GiO5Tii1e1c0vyxXUSIazBA3dSCdSWgrUqOouVe0AVgNX9OhzBfCQ+/oJ4Dxx8jCvAFaralBVdwM1rr24Nt17lrs2cG1emWwMVW1R1VdwxKkTVW1V1Rfc1x3ABsCsgBsMA0C0ooMnQfadLb7Mi1LnmlJMRQfxdq0peVxRynCWoKE76YjSZGBfzPtaty1uH1UNAyeAsiT3JmovA467NnqOlWiMlIhICfBx4LkE128UkXUiss5k2BkMqelcU0owfaeWF0+mC7JGN+9226cUZ/rOREpZRTqiFO9shJ4bdhL1Gaj2dP3ohYh4gUeAH6nqrnh9VPV+VV2iqksG45whg2GkoSnKDEUsH55siZSsmIoO4ukSy+g+pkwf227oRjqiVAtMiXlfAfQ8Wa2zjysCxUB9knsTtR8DSlwbPcdKNEYq7gd2qOp/pNHXYDCkg5vo4EsUKYk3C0Qpuk8pZvrOivErKkaRjqF1zJCUdETpLWCGmxXnx0lcWNOjzxrgevf11cDz6nxNWQOsdDPnqoAZwJuJbLr3vODawLX5ZIoxEiIid+CI11fT+DkNBkOadEZKvviiZFtePGRHokOv6TuikZI7bRdqx5A9pNw8q6phEfkS8AzgAX6mqltF5DvAOlVdAzwIPCwiNTjRy0r33q0i8hiwDQgDN6s6sXM8m+6QtwCrXUHZ6Nom0RiurT1AEeAXkSuBC4FG4J+A94ANbv2re1T1gb5/TAaDIRZx12G8Xn/c62r5smbzrMQWZI2N4KJrSWEjStlEWhUdVHUtsLZH27djXrcDccs2q+qdwJ3p2HTbd+Fk5/VsTzZGZQLX+35WuMFgSE00JdwXX5QQLx4yXSU8TqRkdUVK7cEOAkCwvYWcDPhniI+p6GAwGPqOHcZWwZsoJdzjw5s103cxjznLi9dNdNh5uAGAg8cahto1QxKMKBkMhr5jhwjhwUowF6GWN+OiFD3MT3qsKUXXumw3WcMTCQ69a4aEGFEyGAx9RuwwYTzdHvjdsHx4sbuKomYAO+KIknaLlHx4XLHyutN4lm1EKZswomQwGPqM2CHCyZaks6CEjxAn0cHyOKJk250JD14TKWUVRpQMCXnjdz+Bfymmva0l064Ysg03UkqEZkEJn85D/mLynTRa1dwOdSY8eEyklFUYUTIkpHLT9wE4fuxghj0xZBuWHSYiSapsR0UpgxtTo5tnrdiFr05RCiPumpJXzebZbMKIksFg6DOpp++ca3Y4c5FS/Oy7mGnF6PSdiZSyCiNKBoOhz4gmn74Tj7N/KRTK3ANfo6UxY5IxNJrCbkc6IyWfEaWswoiSwWDoM2JHsJNM34n78I+EMliB2+59HLrErCmJewihTzsymiVo6I4RJYPB0GfEDhFJNn3nRkqRTEZK8Y7OiJm+E/doCwvbHF+RRRhRMhgMfcbSMBFJLEriVg8PhTKYRBCtfRdz7Hk0K1DtMBKbGRhuG1LXDIkxomQwGPqMI0pJpu8sN1IKZ06UorXvYjf4WlZ0WrEDiY2kTKXwrMGIksFg6DOWHU46fWd5M59917mmFFuXObrWFe7ofly7qRSeNRhRMqTGLAIbepB6+s6pux3O4JqSHY2EYlLCOxMwImHENqKUjRhRMhgMfcbSMHZSUXKm7+xwBtOto/uUYo5Dj04r2iEnUoqoG0WFzJpStmBEyZCaREU3DaMWT8pIKRcAuyNzEYho782z4k4rht3pu2YcP8mkeBq6YUTJkBozfWfogWgEtRInOnj8AQAiHZmLQOxoyrcVI56eaATXgaWRGFEykVK2YETJkBA1B/caEuDRMJokUvL63Ugpg1lt6oqSxE7feZy1LjsUxNIwLeqKZ7B16B00xMWIkiEh0dL/BkNPLA1jW8lEKRopZYMoxUR03qgotWNphBY3UuoImkgpWzCiZDAY+oxHI6j4El735WRTpNQlnuJzRCkSCuLRCM1upBQ2kVLWkJYoicgKEdkuIjUicmuc6zki8qh7/Q0RqYy5dpvbvl1ELkplU0SqXBs7XJv+ZGOISJmIvCAizSJyTw+/FovIO+49P5KEx2Qa4mGm7wyJ8BDu3PMTD68rSpoVotT1mLN8jghpuL1booMRpewhpSiJiAf4CXAxMAf4lIjM6dHtBqBBVauBu4FV7r1zgJXAXGAFcK+IeFLYXAXcraozgAbXdsIxgHbgW8A34rj/n8CNwAz3z4pUP6+hCzN9Z0iEV8OolThS8kcjpQzu/4k3fedxRcnuaMfCphUTKWUb6URKS4EaVd2lqh3AauCKHn2uAB5yXz8BnOdGJVcAq1U1qKq7gRrXXlyb7j3LXRu4Nq9MNoaqtqjqKzji1ImITASKVPU1VVXgv2NsGQyGk8BDpOvAvDj4A25WWyYLsrr7lGJFqXOtKxTEo2Ga1PEzk2tfhu6kI0qTgX0x72vdtrh9VDUMnADKktybqL0MOO7a6DlWojGS+V2bwm8ARORGEVknIuuOHj2axOToIjp9Fz3B02CI4iVFpOT1EFQfmtFIyXmMWJ7eoqShdjxEaJPMp64bupOOKMVbWOg5r5Ooz0C1p+tHOj71blS9X1WXqOqSsWPHJjE5uohO34mYfBhDd3waRt09P/HI8XkI4sto+Z7o9B2xkVKOO30XDuIlgnj8BNWLPRQVHewIHNw8+OMMc9J52tQCU2LeVwAHEvURES9QDNQnuTdR+zGgxLXRc6xEYyTzuyKF3waDoa/YNj6JoO6en3j4PRZBvEgkg5US3AjfihEln7umRIezhuTx+gjiH5qEjDfug/86F/a8OvhjDWPSEaW3gBluVpwfJ3FhTY8+a4Dr3ddXA8+76zhrgJVu5lwVTrLBm4lsuve84NrAtflkijHioqoHgSYROctdq/rrGFsGg6GfdE7JJYmUfB6hA39Gy/doZ0WHLlHy+5xpRQm1AOD1+mjHPzSR0p5XnP/vfW3wxxrGJDk60kFVwyLyJeAZwAP8TFW3ish3gHWqugZ4EHhYRGpwopeV7r1bReQxYBsQBm5W9zjIeDbdIW8BVovIHcBG1zaJxnBt7QGKAL+IXAlcqKrbgJuAXwC5wNPuH4PBcBKEQ0F8AN7EoiQidODDymCk1Jl9F7Om1BnBhdxIyeejvdU3JAVZW+sPkAc0HdpJ4aCPNnxJKUoAqroWWNuj7dsxr9uBaxLceydwZzo23fZdONl5PduTjVGZoH0dMC/eNUP6mEQHQyyhYKsrSomn7wA6xJ9RUSLO5lm/1yKIr1OUvF4/Qfz4h2DtK3R8PwANB3cZUUqCWcE2GAx9Ihx0hEY9gaT9QuJH7MydPBv9MhWbfef3Wk4EF3am73w+H+1DlJCRG25yfGg9POhjDWeMKBlSYoqEG2IJu3t6LF/ySCkkPjxZECl1W1PyWnSoF080UvL5acePNdhrX+EgfnU+t0CoYXDHGuYYUTIYDH0i7GaqSZI1JYCw+LEyGSnFqejgrCn58UScNSTL46MDP1ZkkCOltuMANGgBhXZj1wGEhl4YUTKkxoRKhhii1Q8kxZpSxPLjzaAo4R6H7umR6NCBF2/YiZTE46FN8vC603mDRrsjSrt1Ah7szveG3hhRMhgMfSLiRkqWN/maUtjy47WzocxQV6KDZQkhfPgiUVHy0WrlkxNpHlxn2qKiNBGAjqYjgzveMMaIkiElSbaDGUYh4Q5HaCTFmlLECuDVzImSRNeUPN1PyA2JH687fYflpd2TT2DQRclZR9pvOZXOThw7NLjjDWOMKBnSwMx/G7qInpHkSZXoYAXIsTNYZkh7H10BTgKG325zr/lotwoI2K2diRGDQbjVKT7TVlwFQHO9EaVEGFEyGAx9IipKqbLvwt48AprB6tvRNaUe1cyDEsCrIQDE46XDV+BeaBo0V9qbHFHylFc7Q50waeGJMKJkSInaZvrO0EW6a0oRbx45dAxqBJKU6JpSj8MIg1Zu52vx+Ah53K2s7ScGzZUOV5QKJ80EINR0bNDGGu4YUTIkxBzyZ4iH7Z6RFD3yPBHqy3dedAxyZltCBxxR8vRYU4oVJcvjIeR3RSnYOGiuhFqP06wBpo4vp1kD2C1GlBJhRMmQEjXiZIghmhLuy0keKeHLc/4fysyprl0FWbs/5jqsvK43nhwIFDmv2wdPlCJtjTSTy7iiAMcpRFqTHXAwujGiZEhI9JA/TO07Qwy2W/3AnyJSwp/ZSEk0QlgtLKv70WohT4zfvhysQInzehAjJW0/QZPmUZzro8lTgi9YN2hjDXeMKBkSYqbvDPGIuNN3OYHkomTlOKIUahvkdOsEqNpEsLCkuyiFvV2RkngDePOjkdLgrSlJsIlmcinO9dHqLSbQYUoNJcKIkiElZp+SIZbogXipRcnJamtvHbyHfVLsCIrg6SFKGiNKeAN488sACDUPXvRidTTRpLkU5XoJ+kvJi2ToMxkGGFEyGAx9QsNBbBUCOclTwj0BR5Q6WjMTKYlGnEipx1NOo9OKOKWScgrLCKtFxyCmaXtCzbRaeeR4PUQCYyi2jSglwoiSISUmUDLEIqFWWskh4Et+HJs3Kkptg7f/Jyl2/Ok7/AWdLy1fgOK8HOopIjyIpX/84WaCHmdcO6+MAB3YwQxlJWY5RpQMqTGJDoYYJNxGOzm9Egh64st1Uq3D7ZmJlNAIETy9pu8kNlLyBSgKeDmmxWjz0UFzJSfSQtjriJKVPxaAJlPVIS5GlAwGQ5+wwm20k/zYCgB/VJQyFCmJHSaMRc9AiUDXua8ef4CiXB/HtAhpHSRRsiMEtI2IWznCX1QOQGOdEaV4GFEypMbM3xlisCLtBCX5ehJATp7z8I9kaJrK0hBhvEgPVYrkje98Lb5cigI+jlGMt22QNrS6qeaa43weuSXO+M0NptRQPIwoGQyGPuENt9EhKTbOAoE8dw0lmKFEBztMGE/vC262HYDPEopzfdRpEf7B2jsUramX46Se55c6ohQ8YY6viEdaoiQiK0Rku4jUiMitca7niMij7vU3RKQy5tptbvt2EbkolU0RqXJt7HBt+k9ijK+JyFYR2SIij4ik8S/J0AtT0cEQi8dup8NK/U8pL8dHk+YOaqHTZIi7ptST2KzBHJ+H0jwfdRTji7TDYAioWylCch1RKi5zzlQKNQ3eGtZwJqUoiYgH+AlwMTAH+JSIzOnR7QagQVWrgbuBVe69c4CVwFxgBXCviHhS2FwF3K2qM4AG13Z/xpgMfAVYoqrzAI/bz2AwnAS+SBshK/X0Xa7fQyN5WMHMpD+LHYorSnk+D5/puI2/Cv4LAZ+F12PR4neSD2g8MOB+hNucn9+bWwxA6ZhywmqZ+ncJSCdSWgrUqOouVe0AVgNX9OhzBfCQ+/oJ4DxxJnKvAFaralBVdwM1rr24Nt17lrs2cG1e2c8xALxAroh4gTxg4H/jRgFm86whFp/dTiiNSCnf76VR87A6MhMpWXaYsPROW8/ze3jVns8GPZUcryNarXmTnIsn9g64H62NTvUGX75Tzsjj8XBcirBaTamheKQjSpOBfTHva922uH1UNQycAMqS3JuovQw47troOVafxlDV/cD3gL3AQeCEqv4p3g8oIjeKyDoRWXf0qAmpe2FSwg0x+OwgYU8aa0o+i0by8XVkrqJDvEgp19/VFvA5j8BwYRl/MGsAACAASURBVIXTcHzgRamt2RGlQH5xZ1uTVYwvaIqyxiMdUYq3GaHnV+dEfQaqvc9jiEgpThRVBUwC8kXkujh9UdX7VXWJqi4ZO3ZsvC4Gg8HFr0EiVopirICI0GYV4OsYvEKnybA0hC29Rakw4Ot8HY2UvMWTnKSI4/t69T9ZOpqciCinqOvZYurfJSYdUaoFpsS8r6D3NFhnH3eqrBioT3JvovZjQIlro+dYfR3jfGC3qh5V1RDwG+DDafy8hh6Y2TtDLDnaTiTFAX9R2ryF+MMZmr7TMBF6T9+VF3TtsYpGSuVFeRzQMnQQIqWwW1Mvr7i8s609p4zCsImU4pGOKL0FzHCz4vw4yQJrevRZA1zvvr4aeF6dhYg1wEo3c64KmAG8mcime88Lrg1cm0/2c4y9wFkikueuPZ0HvJvex2IwGOKi6pwm60sdKQF0eIvIjWRu82wkzppSWUFXkkae37leXpBDrV1OpOGDAfdDW+to1DxKCroKwQZzJ1CmdeYbXxxSipK7fvMl4Bmch/pjqrpVRL4jIpe73R4EykSkBvgH4Fb33q3AY8A24I/AzaoaSWTTtXUL8A+urTLXdn/GeAMnIWID8I77s97fj89o1GMSHQydhIN4sLtOlU3V3V9ErrZCJJy68wBjaSTu9F1+zJqSxy2VNLEkwB4dD3U1Ay8UrQ00aAEleV3ThuGCiQQIETTHovcieUVFF1VdC6zt0fbtmNftwDUJ7r0TuDMdm277Lrqy52Lb+zPG7cDt8e4x9AGT6GBw0VArAlj+9CKliN89qyjYCHljBs+xOFgaJiJ5vdp7VngAmFKax++0Am/7C9ByFArGDZwf7fU0UMDk3C5RkiInf6vxyAeMLTLr2LGkJUoGg8EAEGxtJACQU5iqKwCa457q2n48I6Jkx5m+A3jqy8u6vZ8yJo/31c3AO/LugIqSr+M4TVKM19M1MeUf4yyDNx/5gLHVSwZsrJGAKTNkSImZvjNEaW9yMsasQFFa/cXdMErb8cFyKSGJpu8A5k0uZt7krhTt0jwf+71TnTdH3xtQP3JCJ2j1dv+8SiZWAtBydOATK4Y7RpQMCTHHoRt6Emx2xMWTpihZbnQUbh76tZNkkVJPRIRA6WRarAI4sm3gnFClMFxPq697lDhh0jTnYMH6gU9BH+4YUTKkgREng0PQPdrck1ecoqeDVeQUH20/PvTHNHj6IEoAU8vyeV+q4MDGgXOi/Tg5GqQ10H06sDg/wFEpHZSyRsMdI0qGhKi7L9lM3xmihFocUfKlKUo+V5Q6TmRIlKz0RWnG+AJe6zgFPbQFOlr7NtieV+HVH/bOMmw8CEBH3oRet9R7x5PXWtu3cUYBRpQMCTHTd4aeRNyK1zn56YlSfmExbeondGLozw6ysNEEa0rxmDWhiHWRakQjfYuWOlrgl38Ff/42vHFft0vauN/xpbhnZTY4kTuF8o796Y8zSjCiZEiNiZQMLhG34nWOW1w0FWUFAY5pMXbT0J8d5NUQtuVL3dFl1oRCNtnVzpvaN9MfaPfLEG53Xr/xX2B3baFoO+YkMgTGVPS6LVhUSbnWoxk62iNbMaJkMBjSRtsbsVXIK0gvUiovzOEYxUjL0IuST0OE0zhiI0pVeT7NnhKOBSph91/SH2j/ehALrrjXqTK++6XOS+2HthNUH/njpva6zSp3BLB+3/b0xxoFGFEypMSsKRk6aW+kmVzyctJbqynL93NUi/G2D3H2nSp+Ooj0QZS8HotZEwt5w3O6s0aU7rpS/U5acifz95ursHNKYOPDXW4c3c4uncj44t4VMIonzwLgyJ4BzPYbARhRMiTErCkZetHRTBO53SptJyPg83DCKiUwWEeNJyISwkKJWP7UfWNYPK2U3zTOgkgQ9ryS1j32sRo2tIxh7XsNvBhYDu/+HtwD/AL177FDJzO5pHcFjMmnzAWg9ZCJlGIxomRIAyNOBgcJNtFKLn5v+o+OFn8ZeeHjEO4YRM964K7x2J70IyWAMyrH8EpoJrYnAO8/nfoGVexjNdREJnBaRTGrjp4JkQ7Y9Gto+ID89kNslllMKOpdVb18zBgOMwap29EnH0c6RpQMCelMCbdN7TuDg6/jBM1Wehtno7TkTsJCoXEIM83CQaDvorSkspQgfnaXnQPbnoRIKPkNzUfwhlvYoxP4j5Wns5Op7Ck43UkPX/9zAPaVLMWyetfbExH2+6czpun9Pvk40jGiZEiImb4z9CQQOt6rZE4q2gvcdOhBOKsoIdFsuD6K0rjCANXjCngycja01sGuF5PfUL8TgKa8qVSV53PJ/Il8o2kl2n4CXrmbN2Q+BZPnJLy9sWQ2k8N70VB7n/wcyRhRMqREjTgZXPIiJ2j3ppcOHkWL3MyzIRUlJ1JSX3qHEcZy3uxx/PTgKWigBDavTt65rsYZp8zJpPubc6pYF5zC70+/n7ozvsHft/09SyoTF6K1Js7HR4Sju9/ps58jFSNKBoMhPVQptBvp8PdNlPLKpxJRIVS3Z3D8iocbKUmaJ+TGcv7s8bTZHvZMuhTeXQPNidPZtW4nITwUjp8GwIKKEs6sGsPtGwv4l8bLqJdiPjIz8dEU4049A4CD2/uwL2qEY0TJkBqTEm4ACDbhI0wkt7RPt00sK+QQY2g7unuQHOuNnoQoLZpaSlm+n4fCFzhJC+t/kbBvx5Ed7LXHMW1sl1DfedU8gmGb328+wOWnTYqbeRdl+qkLaNEcQrUDWG9vmGNEyZAaI0oGgLZ6ADTQt3ORJpfkUatj0YY9g+BUfELBNgDE17c1JXBOo71i4WR+tTOHUNVyeOvBzunAnthHa9ilE5le3rUPqXpcIU//n3P44cqFrPrEgqRj+X1edvpnUlq/qc9+jlSMKBkMhrQIuUd3S35Zn+6bXJpLjT2ZwPEdQ/YFJ9ThiJLVjzUlgGuWVBCKKM+XfhKaD8GG/+7dybbxN+5ht06kqrz75thpZflcsXAyAV/q2nsNZYup7Kgh7FZgH+0YUTKkxkRKBqClwVlb8RaU9+m+8YU51FBBTqgRmoemMGukvRlI/9j2nsyeWMSCimLuen8COuVD8PL3IdTWvVPjfjx2kL1MoKK0f+MA5Ez/MB5RPnj75X7bGEkYUTIYDGnR3OAcP5FX0rejwr0ei2O5pzhvjrw70G7FJdzmFDmVNI9tj8cNy6rYeayVddNvgqaD8NYD3TsccyoxtBRUdTvqvK/MWLyciAp17yWvt2fbSmtHOGmfkUBan6SIrBCR7SJSIyK3xrmeIyKPutffEJHKmGu3ue3bReSiVDZFpMq1scO16T+JMUpE5AkReU9E3hWRD/Xt4zGASQk3OHQ0OJtfC8f2rnidilDZTOfFAB81ngi7PSpKBf22cen8iUwZk8u/v1uOVp8PL66CpphzofY7yQkd4+adlK9lZeXs9lZRcPD1pP1W//J+HrvzevYdG9lVxVOKkoh4gJ8AFwNzgE+JSM/dYDcADapaDdwNrHLvnQOsBOYCK4B7RcSTwuYq4G5VnQE0uLb7PIZ7zw+BP6rqLOA0YGi+po0QonvQTUFWA0Ck8SCNmktZad/WlADGT6ygTovRg5sHwbPeRI+DkEB61czj4fVY/O25p7Bh73FeO/WbTj28Z/6pa4zat9itE5kwbvxJ+3u4/MNUt28h2HI87vVIxOaqnf/M5+QpNr/w2EmPl82kEyktBWpUdZeqdgCrgSt69LkCeMh9/QRwnoiI275aVYOquhuoce3Ftenes9y1gWvzyv6MISJFwLnAgwCq2qGq8f/GDQZDSjxNBzmsYygv7FuRU4Dq8YWst6uJ7B2a/Th2exNhtfD1c00pyrVnTGF6eT7ferkN++yvwZYn4O3HoaMV3f0XXo7Mo7K8dwXwvhKYfSF+ibDrzT/GvX5sfw254tQO9O958aTHy2bSEaXJwL6Y97VuW9w+qhoGTgBlSe5N1F4GHHdt9Byrr2NMB44CPxeRjSLygIjE/e0RkRtFZJ2IrDt69GjiT2K0YiIlA+BvO8IxKSXPn/4R41FmjCtgvX0q3oad0DIEFcM7mmkhgD+N7Ldk+DwWt1w8i51HW/hVzjUw9cOw5svw+Oewwm38PvIhTh3X/ynCKLOWXkCL5tC8Lb4o1e91Jnk68DK1eRPhyMitR5mOKPWuJNi7bHSiPgPV3p8xvMAi4D9V9XSgBei1Hgagqver6hJVXTJ2bOLd16MNI0WGWPKCRzjh69+/D0eUZjhv9r0xgF4lINhMM7nk9KGaeSIunDOes6vLWPWnXRxc8V8w8TTY8Qxbx32cdcxi3uT+TxFGyc/L4/28RUw+9mrcAshth51yRjvGraCaWnbsH7lfntP5G6sFpsS8rwAOJOojIl6gGKhPcm+i9mNAiWuj51j9GaNWVaP/Ap7AESlDHzFrSgZsm6JwHS3+vmXeRSkryOFg/mw6JAd2vTDAzvVGg820aID8NA8jTIaI8N2/WoCtyi1/PIT9uafhlj38u//LzBhXMCBjAISnn88kPcLu99b3umbX7aRdfYxZ+HG8YrPn3XUDMmY2ko4ovQXMcLPi/DhJBWt69FkDXO++vhp4Xp0n2RpgpZs5VwXMAN5MZNO95wXXBq7NJ/szhqoeAvaJiJv2w3mAOeLRYOgPzYfwEiFcMKnfJuZOHcdb1gLY/sdBnxL2tNfTQOGACcaUMXncdvEs/vL+Ue5+bgd1kTze2F3Hx2b2T6TjUbXsGmwVjrz+eK9rOU0fcMCawIRZZwLQsmfDgI2bbaT8G1PVsIh8CXgG8AA/U9WtIvIdYJ2qrsFJJnhYRGpwopeV7r1bReQxHDEIAzeragQgnk13yFuA1SJyB7DRtU1/xgC+DPzKFb5dwOf79SmNdkykNOqx63ZhAVpa2W8bp08t5ffbT+PsyANweCtMOLlU6mT4gvXU6xiq/Ce3phTLdWdNY8v+Rn78fA2Pr6slbCvXLOl7enwiyidOY5tvNuP3PwPc1e1aftshjvsmIKWVtFgFBI5tGbBxs420vkao6lpgbY+2b8e8bgeuSXDvncCd6dh023fhZOf1bO/PGJuAJfHuMaSPMnIXVQ3p0XRwB8VAYHx1v20smlrCg5HF2P5fYL29GibcMXAO9iAnWE+9Vg5YpATONN6dV81jQnGA5947zNcumEH1uP5vzo1HY9XFzNnxffbueJupM7rq5pWGj3CodA6IUF84k4qGHTS1h9I+ln44YSo6GAyGlLQeep+QeiiZOL3fNk6bUkKTt5T3ipc5x4UnKHJ60tgRAqHjHKOI3JPMvuuJ12PxtQtO5akvn8O1Z0wdUNsA08/9NAB7X+k6x6mjtYlSGrELnahMJp7GLNnL23uHIIsxAxhRMqTGTN+NeiJ1u9mv5VSU9T8yCPg8fOiUMn7e/lHnVNfNjwycg7G01iMozVZx3GPIs5lxU6qp8Z3KuH1/7EwwOrLfOd3WV+ac2TRmxpkEJMTeOAkRIwEjSoaEmOPQDVH8J3bzgY5nUpKzgdLhYzPH8fjxGbSPXwwv3dW7yOlAcMI54bbOO2HgbQ8BjdVXcqq9kx3vvAVA/YFdABRNqAQgr9I5GLDjg7cy4t9gY0TJkBoTKY1uImFKW3ay31/Vr42zsZw3exwgPDX2i9C4H17otRR88rjnNjXkDE9ROuW8zxNSD8de/TkAre4epfIKd5/XmOm0WoUU1r8zIrdrGFEyJETdfckj8Pfe0BfqavBpiKaSman7pqCiNI+zq8v44a7x6KLPwf/eA+8/c/I+xlLvnHDbmj8lRcfspLh8ElsLzuLUw3+gPRjEOvY+LRqgbEKV00GE46XzmRXZQW3DIESaGcaIkiEhZvrOAGAfctKPZfzApHBfs3gK++rbeHn6V2HiAnjsetg5gBtqD73DIWs8eflFA2dziMk547OUc4L1f/o1+ce3s983FSvmeAzvlMWcKvt4e/fBDHo5OBhRMqSBSQkfzTR9sJGQeiidNjCidMn8iUwqDvAffzmAfvpxGFMFv/wE/OX/g3BH34ypwsG3u8J5Vahdx1aqKc3re+HYbGHWsk+w35rAlA2rmBHcSt2Y07tdH3PqWXjF5sj7Q1PgdigxomQwGJIS+eB1tuo0qieOGRB7fq/FTR+rZsPe4zy7D/jCMzDncnj+DvjJGfDGf0HLsfSM7XwO/uscePHfnfcHNkBjLS+G51GaP3xFSbx+Gs78JlP1IH6JULqk+xZN7xRn+6XsH3nlhgZuZ5lh5GIWlUYv4SBFdW+zQc/n0xMHbjrs2iVT+NXrH/Ct323hzH84l6JrfgELPwMvrYKnvwlP3wIVS2DyYpgwH0qmQeFEyBsDlgfsCBzbAS//wDH40ioINsPe19CcIp48sZgb84b3xtJ5F93AFlXCKixcekH3i4UTqM+pYErjRjrCNv4BKDybLRhRMiQkuqZkJGkUc2AjXu3gUMnpBAZwI6rfa/HdTyzgE//5v3xt9Sbu/+sleGZcADMugIOb4b21TuHWDf8NodbEhjw5sGIVHNgIr98L3gB1F/yQxt8WMK4wMGD+Zop5K/4m4bXmCWexZM9a3t3fwGnT+n7wYrZiRMmQGhMpjVrsXS+BCta0Dw247YVTSrj943P49pNb+affvsOdV83HY4lzNMTE0+BjtzkRUcMeOFHrHEXeVg9qAwIlU2Hah53oCeCSu8DysmNfO/A6k0tPbk9VtlMw6yMUf/AEH7z7FqdNW5FpdwYMI0qGhERTwo0ojV7atvyB7XoKc2acMij2//pDlRxtCvLj52uoa+nge1efRnHstJvlgbJTnD+pcI8+33+8AYDJJ7nRN9spnf1ReAbad7wEK0aOKI2ciUjDgGNSwkc5jQfJP7aZZ+3FLKsuH7Rhvn7hTG7/+BxeeO8IF//wLzz9zsGT2hS6t74VS2BiyfCfvkuGlEylzjeRsrq3RtRJtEaUDAmJVg1TI06jk22/A+CD8o8yZpAz2T5/dhX/c9OHKQz4uOlXG7j6vtd4ZushInbff/e2HWhk+tgCcrwDW4w1G2mdeBaL9F3e3lefaVcGDCNKhiQYMRq1qBJe9xCb7elUzx2a019Om1LCH76yjDuvmsehE+387cPr+dj3XuRHz+2gtiFJskMMqsqW/SeYM4CZgtlM6fyLKJVm3t/4cqZdGTCMKBkS0jl9Z9aURh/71+M99i6PRj7G5Qv7f9psX/F6LD5z5jRe+sePcu9nFjGpJMAP/vw+y1a9wMr7X+PxdftobA8lvL/mSDOHGttZWjUwe6qynYI5F2AjUPNcpl0ZMEyigyEhXWtKI2e+2pAe+vL3aZYCasav4JSxBUM+vtdjccn8iVwyfyL76lv57cb9/M+GWv7xibf5p99u4SMzx3LZgomcP3t8t4P8Hl9fiyVw/uzxQ+5zRsgv50j+TKqb3qSxPUTRCDj0z4iSISHD6yQaw4Bx6B1k+1oeCH2Cy5eefBHWk2XKmDy+ct4Mvry8mo37jvPU5oP84Z0D/HnbYQI+i/NmjWf5rHHUt3Tws1d2c+XCyUwoHtlJDrFEpi9n4dv38dJ7ezhv4YxMu3PSGFEyJETcCMnM3o0iVGHtN2m2Cvmt/zKeWVSRaY86EREWTS1l0dRS/vnS2by1p56n3j7I2ncO8od3nMKkS6vGcPvlczPs6dAy7vRL8b5zL4c2PgNGlAwjGVFMuDTa2PQr2Pu//L/QF7l6+Xxy/dmZwWZZwpnTyzhzehm3f3wOe+pa8FoW08ryEBldv7S+aWfSJnkU1L6E6s3D/udPK9FBRFaIyHYRqRGRW+NczxGRR93rb4hIZcy129z27SJyUSqbIlLl2tjh2vT3dwz3mkdENorIU+l/LAYwiQ6jjqPvo2u/yRbvPF7Ku5C/Oacq0x6lhddjUT2ukMry/GH/QO4XHh9Hx57F4vAGdh9tzrQ3J01KURIRD/AT4GJgDvApEZnTo9sNQIOqVgN3A6vce+cAK4G5wArgXlckktlcBdytqjOABtd2n8eI8e3/AO+m93EYYjGiNIporYdHr6MdHzc0/x23XTr3pE+ZNQwdBXMupEKOsXnT8D8iPZ1IaSlQo6q7VLUDWA1c0aPPFcBD7usngPPE+cpyBbBaVYOquhuoce3Ftenes9y1gWvzyn6OgYhUAJcCD6T3cRgMo5BgM/z6k9j1u/li65c4Y8FcLj9t6NLADSfPmNMuBqDtvT9n2JOTJx1Rmgzsi3lf67bF7aOqYeAEUJbk3kTtZcBx10bPsfo6BsB/AN8kRU6ziNwoIutEZN3Ro0eTdR1VWJ2JDiYlfMTScgwe+ji6fz1f169woPQM7rxy/uicBhvOlFZyNGcqFXX/SzAcybQ3J0U6ohTvt7PnfE6iPgPV3ucxROQy4Iiqro9zvXtn1ftVdYmqLhk7dmyq7qMG81ga4RzeBg9egH14K9/0/CMvWWfx88+f0b0gqmHY0Db1YyxlKxtqhvcR6emIUi0wJeZ9BXAgUR8R8QLFQH2SexO1HwNKXBs9x+rrGGcDl4vIHpzpweUi8ss0fl6DiynIOkJRhfUPwU8/Rqj1BF+wv8WLspRHvngW08ryM+2doZ+MO/1SAhJiz4bhPYWXjii9Bcxws+L8OEkFa3r0WQNc776+GnhenTK/a4CVbuZcFTADeDORTfeeF1wbuDaf7M8YqnqbqlaoaqVr/3lVvS7Nz8UAmNp3I5Dje+GRlfD7r1BbuIBljXewN38+T/zdh5g5oTDT3hlOgsCMc+nAT84Hz2falZMiZXqNqoZF5EvAM4AH+JmqbhWR7wDrVHUN8CDwsIjU4EQvK917t4rIY8A2IAzcrKoRgHg23SFvAVaLyB3ARtc2/RnDcHJY0ZNnTfbd8CcchDfugxe/i63wcOEX+deDH2HF/Ems+sQCCkdAeZpRjy+Xw2MWs+DYOg6daB+2VS3EPHC6s2TJEl23bl2m3cgKIreX4BFl44d+xOkXXZ/6BkP2YUfgncfhhTvh+F5qxpzLDYc/SYNvHP906Ww+uWSKSWoYQRx65gdMeO1feWr5M1x27llDOraIrFfVky4pb6qEGxJiHlXDGNuGd5+C+86B3/4tdZE8brb+mfMP/B0L5s3j2a9/hGvPmGoEaYQxftGlADRt+WOGPek/ZnecISGWmOm7YUe4w4mMXv0hHNtOY+4Uvuf7Og8fPZ0zp5fzu4tns3BKSaa9NAwSUn4q9b4JjD/yChFb8VjD70uHESWDYSTQ3ggbH4bXfgKN+zmSP4Pvy1d5omExiyrL+fnV1Xzk1LEmMhrpiNA4+SOcsXsN73xwhIVVw+8IDyNKhtSYSCl7OfIevPVTdPNqpKOZmryFfDfyWZ6tm88Fcybw2Eems3ja6DjwzuBQvvASCvY8yo4Nz7Ow6lOZdqfPGFEypMRoUpYRCcP2P8CbP4U9LxOx/LzgXcaPgh9jp30qVy2ezLMfrqR6nEnxHo0UzFpOGA/WzucAI0oGg2GwOFELm36Nrvs50nSABt8Efm5/mofbz2XixAquO28aly+cREGO+Wc9qgkUcbDoNGYdf5MTraFhV6HD/PYa0sDUvssY4SBsXwsbHkZ3Po+grPcs5L6OT/G/kcVcPL+Cn501lYVTSsx6kaETmXE+c9ffxbPvbOP8M0/LtDt9woiSwZCNHHoHNv4S3fwo0t7AMc9YfhW+iscj5zKpchZXL6rg7vkTzKZXQ1wmLLoM1t9F3dtPgxElw4jDLCoNDW0N8M4T6MZfIgc3ERYff7KX8OvQR6ktXsJVH5rGI4smM2VMXqY9NWQ53kkLOOEZQ+nBl1G9ZVhF0UaUDClRUwNv8Ai1w45n0LcfQ9//E5bdwXYq+XXoep7zfoRzFszg/yyuYMm00mH1YDFkGBHqJy7jjH3P8/7BE8ycNHz2phlRMhiGGtuGD15F334Me+vv8HQ0UkcJvwufx1Ocy+TZZ/Hx0ybyf2eOI+DzpLZnMMShZMEllNau4aX1LzFzUs9zWbMXI0qG1Jjpu4Hh8FZ4+zFCmx/D13yANgI8HTmD3+syfNUf5bKFU/jl7PEme84wIJTOuwh7rRDZ8Wd6HxaevZjffoNhMDm+D7b+huCGR8ipe5cIFn+JnMYa+69onnYBF51+Cj+cO2HYpe0ahgF5YziYP5uq46/THooMm6jbiJIhNSZS6huNB9Ctv6Vt0/+Qd9g5+HirXc3vItezf9IKPrJoDv88byJjC3My7KhhpBOeei7zt/2U9TtrOWvWtEy7kxZGlAyGgaDpELr1d7RsfIKCw28hwB57GmvtT7J34goWLVzETfMmMLE4N9OeGkYRYxecj+/d+zjw9gsw63OZdictjCgZ4mJHIl3nmphIKT7NR7C3PknzhscpPPwmgrLPnsLT9jUcrFjB6acv5XNzx1NeYCIiQ2bIO+VsQnjxfPAy8LlMu5MWRpQMcQmHQ/g73xlR6qTlGJGtT9K04XGKDr2Bhc1hezK/0E9wdOrFnLboLL4wexwlef7UtgyGwcafx8HCeUw/sWHYrCsZUTLEJRLqyLQL2cPxfQS3rKF5028pPbYeDzZ19kR+zVXUTbuEBYvO4vOzx5vqCoasJDL1HOZsuYd1NR9w5uzpmXYnJUaURjjrf3M3xdMXU73w3D7dFwqHiK5+jMpD/o5up3nTbwm+8yRljdvIAXbbU3jCuoqmqkuYt+jDfH7meHL92f/N0zC6GX/a+Xi2/piDm58DI0qGTLP47X+Bt4GFJ/p0XyjYOij+ZC2q6IGN1K/7H2T7U4xp3UMBsMOu5rGcv8aeeRmLFy3hhmmleD1WSnMGQ7aQN/1DBPHj2/cq8MVMu5OStERJRFYAPwQ8wAOq+t0e13OA/wYWA3XAtaq6x712G3ADEAG+oqrPJLMpIlXAamAMsAH4rKp29HUMEZni9p+AU+b6flX9YV8/oOGM2jb9LUwTbG2JMTRCIyU7QnjP/3LszSfI3fU0xR2HKVaL1+3ZbC26Cf+8j/Ph0xfwd+MLK7GwnAAAEYlJREFUTIkfw/DFm8OBogWccmL9sFhXSilKIuIBfgJcANQCb4nIGlXdFtPtBqBBVatFZCWwCrhWROYAK4G5wCTgWRE51b0nkc1VwN2qulpE7nNt/2c/xggDX1fVDSJSCKwXkT/38HtEE2xvJdDPezvammLejSBRCjbT9t6fqdvwJCW1z1MQOUGJ+nhFF7Cr/K8pWfhxzj1tJsuK+/vJGQzZhz3tHGa9czdvvr+TpXNPTX1DBkknUloK1KjqLgARWY1TsyL24X4F8C/u6yeAe8T5ankFsFpVg8BuEalx7RHPpoi8CywHPu32eci1+599HUNVXwMOAqhqk2t7cg+/RzRtLU39F6X2ltSdhgl6fC/HNqyhfcsfmFD/FrmEKNQ8XpJFHJ18AROXXMbZcyo535T3MYxQJiy8EN65m8NvPwcjQJQmA/ti3tcCZybqo6phETkBlLntr/e4d7L7Op7NMuC4qobj9O/PGACISCVwOvBGvB9QRG4EbgSYOnVqvC7DkraWRkr7eW84RpSGXaKDbdOxbx0H3/wdObv+xIS2HYwFdtkTeDJwCcHpF1K95HwurBqHz6wPGUYB+ZVn0Cq5+Pe9AtyUaXeSko4oxZtM7/mUStQnUXu8J0Gy/v0Zw7lJpAD4H+CrqtoYpy+qej9wP8CSJUuG2RM4McHWuD9uWoTbmwfQkyGgo5WGLX+ibuMayg+8QEmkngoVNjCTl0q/SGDeZSxatJSrzVlEhtGIx8fBwvlUnnibYDhCjjd715XSEaVaYErM+wrgQII+tSLiBYqB+hT3xms/BpSIiNeNlmL793kMEfHhCNKvVPU3afysI4pgS98y7mIJtcUKWnbqdOT4fmrf+C3hd9dScfwtSunAq7m86VlE/dTljF98GWfMnsEZJm3bYMCuOIsZJ37M27v2svDUqky7k5B0ROktYIabFbcfJ6ng0z36rAGuB14DrgaeV1UVkTXAr0XkBzhJCDOAN3Gim1423XtecG2sdm0+2Z8x3PWmB4F3VfUHff1gRgIdriiF1ENft3VGmo52vpZsmb6zIzTvepP9bz1J3gfPMaX9faYBe3Ucz+VfTLh6BTPPvIjlk8aYbDmDoQdj5y3H2vYjDm15AYazKLnrN18CnsFJ3/6Zqm4Vke8A61R1Dc7D/2E3yaAeR2Rw+z2Gk1wQBm5W1QhAPJvukLcAq0XkDmCja5u+jiEiy4DPAu+IyCbXxv9V1bX9+6iGHyF3+i6Iv8+iZLfUDbxD/UBbG9i/7ilatj7NxCOvUKQnqFZhs8xk89gvkr/g4yxa9CEuyTdlfQyGZJTMOIsQXvjgNeALmXYnIWmlG7kP8rU92r4d87oduCbBvXcCd6Zj023fRVeGXmx7n8ZQ1VeIv940aoi0OZFSUPwU9PFeq61LlIY00UGV5n1vs//NJ/Htepapre9QgU29FrA+Z8n/397dB1V13gkc//64XBSMCgIaBBUV5EURwTd8iU1jqiaNtmNMaptOskmnzWyyM012u3lZd7e17UybpLPd7Uy6mbTNNNlto01bE2u0hiTGrOIb4gsggkB8BUQRUEBA4Nk/zmMhegkvuXgvl99n5s4997nPec5zfnruj3Puc59D46SlxM1dSXpCPJlBQ/qfV6m+cYdyLjSZ8fWHMMb47dUEHQMbwDqanaTUSt/PIoY3nqOO2whn4Ac8mJYGzh3aTv3RrYyr2klUxwWSgGNMJjviG4SkriBt3l18cfSIAe+LUoHs6vh5pJS+TnnFRabGRvu6Ox5pUgpkDc73Qq1Bfb91QkTzWaqC4whvO85ADHRorCrl9N5NBJVlE38ljziuEW6GcyQkg9z4bzNu9irSkpNI1SHbSnlNePKduMte49TRnUyNXePr7nikSSmABTdWARBkOvq03tWGemI6qsgbNRPqj3ulL6athXNHdnDp8F+IrNxJbNsZUoBPTAy7wlfhSl5O8rwVLIoc7ZXtKaVudvuMJXS8K1wr34UzXsz/aFIKYCOuOqPpXbT1UPPTyvM+YLp0YCYuhPy/9nvuu2uNtZTveZvWwi1Mrs0hjiaiTTAF7jSOTVpDVMZKZqRlMFnPhpS6JSQ0grMhU4iqOejrrnRLk1KA6mhvZ0JrOQgEm74lpea8jTSa4cTM/CLk922gw+XzpziZ8xbuE38loSmPJNqpMaM4NHIJHdPuYVrWfcweG9XX3VFKecnlsXNIOfM21XVXGBs+0tfduYkmpQBVvH87KXKVyyYMl7T3er1zJw6TVpvNwciVJIwY1at1Gi9VUrrjfwkr2URiSyEzgVPEsDvqQcLSVpI2/0vcMVyHbCvlD8ISlxB2diOHj+Qw9gvLfd2dm2hSCkCFu95h5IfPc4mRlEbcQVLdzl6tV3/hHG1vfpOrDCfhgR91/mjWw3dSpqOdkt2baNv7K5Ia9pMuHZTJBD6KfZzoeQ+QPGM2k/SynFJ+JzZ9KeyAxpKPQZOSGkjlR3fTtPVfmdGcRyXRnL3rZToKtxJsej5TKs7ZTHj204zrqKfkS79lZsxE6mvOA2DaOm+NbtrbOLrtVaLzfkFSRyXVRJAz7huMWfAQqekLmKq/HVLKr4WEx1DpGs+oCwd83RWPNCkFgIryY1RtWkfmlQ+pZSQ5if9E5urvERMaxp6i9wim+6RUdvBDWt5bT2rLYc4xjvJVm5g5+w4A3MPsjS/amp3tnDhM88bHSG8rozgogZyMl8hY9jBLQvXeQ0oNJhfHzGZa9Q6aWloJG+Zfl9Y1KQ1i50+XcGrzT8i48A7hBJMT9yjTH/g3FoZHdlYKchPsYfTdyYI9XN76fWY27aOG0exO+B4Zq58mNqxz7oeQYaGAc6Z0Ijeb8Vu+yXDc7Ml4kXn3fZskvTyn1KDknrKIiAt/4VB+LhlzFvq6O5+iSWkQOl2cR/W2F0mvfY8I4GDkfUy5/0csjJ10c2WXG5cY2tvbcblcVJYXULVpHRlXPqLejGBX/JOk3/8Mi0aF37RqsDuENhOE+8pporf8HTUyhuBHt7Bg4tSB30ml1ICJnbUU9kFt0U7QpKT6o7npCoXZrxNW8HtSrhUSbULIHbua+JXPkjUxsdv1JMiZirXlagP5G39A5unXGUUwu+MeY/rqf2Fx5GdPNdKKmzm1W2k2bmrXvslETUhKDXojb0/kokQSVpHj667cRJOSH2tuaqA4ZzPXCt5hWt3HzKaJMzKePVO+S+Lyx1kwLrbnRlzOP3HJL7/G/KY97Bu9nMlrf8ai8b27w26YtABwKHoVC5Jn9XtflFJ+RIRzEXNIqNlL67V2Qtz+c88xTUp+puFyLcW7/oQc20zylb2kSwuXGUHx6DsInf8IqfPvYUJfvstxOWdKs5r2kDPpCRY++pN+9St2+VP9Wk8p5Z+CJi8h6tJ2CgoOMCMjy9fd+RtNSn6g7kIlJ3a9RUjJu6Q05TJb2qhhNPmRKwhN/yrJWfcyd1j/RrgF3+bMntBs3Mx/+Md9Xn9/2g9or69iQeLMfm1fKeWfJmYuh4PrqCl4HzQpqQsVJyn/vw2MKN9GcvNR5koHlUSTN24NozJXkzRnKfODP/8/T9ysuzlzaDx1S39Kmqvvp+jz7n/6c/dBKeV/Rscmcl7GElaxx9dd+RRNSrdQ5aliTu3aSPjJbUxrLSJaDKeDYjkQ9zBRc9eQMHMRMUHeHWZ9+8RE+H4RE7zaqlIqEFREzCGx5mNar7UR4vaPdOAfvQhgVxuvUJD9BmHH3mR6az4xQJlrMvviH2d81oNMSplN74YcKKWUd7mmfoHwS1s5lr+X1MzFvu4OoElpwNRdrOL42y+SenYDc2nkrMSwN/4J4hY/xNSEGejAaqWUr02cvQIOPMulgmzQpBSY2tvayP3jS6QW/RdZcpVDIxYTsuhJUrNWEOflS3NKKfV5hN8ez0nXJCLOvA+s93V3AOjVp6SIrBCRYhEpFZHnPLw/TEQ22vf3iUh8l/eet+XFIrK8pzZFZLJt44RtM8Tb2xgo9TXnOfbS3cw//lM+CU3l5Nc+IOOf32X6wnsRTUhKKT90IW4ZKa2FVFec9nVXgF4kJRFxAS8D9wCpwNdFJPWGat8Cao0xCcDPgRfsuqnAWmA6sAL4pYi4emjzBeDnxphEoNa27e1teF3dxSpqX15KUnM++9PWk/bM+8SnzBmozSmllFeMm/8gQWIo++gNX3cF6N2Z0jyg1BhTboxpBTYAX7mhzleA1+3yH4GlIiK2fIMxpsUY8wlQatvz2KZd5y7bBrbNr3pzG70LS9+0tjRT/cpKYtqrKFn2W+bd/5SeGSmlBoWJKXMpck8npeS/qTpT6uvu9Oo7pVjgTJfXZ4H53dUxxrSJSD0Qacv33rDu9blxPLUZCdQZ87f7d3et761t3EREvgN8x75sEJEa4KKnuj364ap+reanouhvHAKPxqKTxsIReHFY3/08mj2IAjzMCN13vUlKnu7aZnpZp7tyT6cRn1Xfm9u4udCYV4FXr78WkVxjzJC/9qZx6KSx6KSxcGgcOtlYxHujrd5cYzoLn/rtZRxQ0V0dEQkGRgOXPmPd7sovAuG2jRu35a1tKKWU8lO9SUoHgEQ7Ki4EZ1DB5hvqbAYesctrgA+NMcaWr7Uj5yYDicD+7tq06+ywbWDbfMeb2+hdWJRSSvlCj5fv7Pc3/wBsB1zAa8aYQhH5IZBrjNkM/Ab4HxEpxTl7WWvXLRSRPwDHgDbgSWNMO4CnNu0mnwU2iMiPgUO2bby8jZ682nOVIUHj0Elj0Ulj4dA4dPJaLMQ52VBKKaV8T8ctK6WU8hualJRSSvkNTUpd3OppiXxBRF4TkWoRKehSNkZEsu3UTtkiEmHLRUR+YeNxVEQyu6zziK1/QkQe8bQtfyYiE0Rkh4gUiUihiHzXlg/FWAwXkf0icsTGYr0t99qUX4OJnRHmkIhssa+HahxOiki+iBwWkVxbNvDHhzFGH873ai6gDJgChABHgFRf92sA9nMJkAkUdCl7EXjOLj8HvGCX7wW24fwWLAvYZ8vHAOX2OcIuR/h63/oYhxgg0y6PBEpwpqMairEQ4Da77Ab22X38A7DWlr8C/L1dfgJ4xS6vBTba5VR73AwDJtvjyeXr/etHPP4R+D2wxb4eqnE4CUTdUDbgx4eeKXW6ZdMS+ZIx5mOc0YtddZ3C6capnd4wjr04vyGLAZYD2caYS8aYWiAbZ97BQcMYU2mMybPLV4AinJlAhmIsjDGmwb5024fBe1N+DRoiEgd8Gfi1fe3Nqc8CwYAfH5qUOnmaTim2m7qBZpwxphKcD2tgrC3vLiYBFSt72SUD5wxhSMbCXrI6DFTjfHCU0cspv4CuU34N9lj8J/AM0GFf93rqMwIrDuD8YfKeiBwUZyo2uAXHh95PqVNvplMaavo6tdOgIyK3AX8CnjLGXHb+0PVc1UNZwMTCOL/tmyUi4cAmIMVTNfsckLEQkfuAamPMQRG583qxh6oBHYcuFhljKkRkLJAtIsc/o67XYqFnSp2G8rRE5+2pNva52pYH9BROIuLGSUi/M8b82RYPyVhcZ4ypAz7C+V7AW1N+DRaLgFUichLn8v1dOGdOQy0OABhjKuxzNc4fKvO4BceHJqVOQ3laoq5TON04tdPDdmRNFlBvT9m3A8tEJMKOvllmywYNe+3/N0CRMeY/urw1FGMRbc+QEJFQ4G6c79i8NeXXoGCMed4YE2eciUXX4uzXQwyxOACIyAgRGXl9Gef/dQG34vjw9QgPf3rgjCApwbmevs7X/RmgfXwTqASu4fwV8y2c6+AfACfs8xhbV3BulFgG5ANzurTzGM4XuKXAo77er37EYTHOZYSjwGH7uHeIxmImzpReR+0Hz7/b8ik4H6alwFvAMFs+3L4ute9P6dLWOhujYuAeX+/b54jJnXSOvhtycbD7fMQ+Cq9/Ht6K40OnGVJKKeU39PKdUkopv6FJSSmllN/QpKSUUspvaFJSSinlNzQpKaWU8hualJRSSvkNTUpKKaX8xv8DM7Nwv4XCekcAAAAASUVORK5CYII=\n", "text/plain": [ "
" ] @@ -895,7 +903,8 @@ "source": [ "plt.clf()\n", "# plt.plot(x_part, calcs, '.')\n", - "plt.plot(test_q, calcs_test, label = 'pdf')\n", + "plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)')\n", + "plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)')\n", "# plt.plot(test_q, f0_y, label = '0')\n", "# plt.plot(test_q, fT_y, label = 'T')\n", "# plt.plot(test_q, fplus_y, label = '+')\n", @@ -904,13 +913,13 @@ "plt.ylim(0.0, 1.5e-6)\n", "# plt.yscale('log')\n", "# plt.xlim(770, 785)\n", - "plt.savefig('test.png')\n", + "plt.savefig('test++.png')\n", "# print(jpsi_width)" ] }, { "cell_type": "code", - "execution_count": 14, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -926,7 +935,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -942,7 +951,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -955,7 +964,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1012,7 +1021,7 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1096,7 +1105,7 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1105,7 +1114,7 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1114,7 +1123,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1123,7 +1132,7 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": null, "metadata": { "scrolled": false }, @@ -1171,7 +1180,7 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1188,7 +1197,7 @@ }, { "cell_type": "code", - "execution_count": 24, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1212,7 +1221,7 @@ }, { "cell_type": "code", - "execution_count": 25, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1239,7 +1248,7 @@ }, { "cell_type": "code", - "execution_count": 26, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1262,7 +1271,7 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1271,7 +1280,7 @@ }, { "cell_type": "code", - "execution_count": 28, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1287,7 +1296,7 @@ }, { "cell_type": "code", - "execution_count": 29, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1317,7 +1326,7 @@ }, { "cell_type": "code", - "execution_count": 30, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1331,7 +1340,7 @@ }, { "cell_type": "code", - "execution_count": 31, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1349,7 +1358,7 @@ }, { "cell_type": "code", - "execution_count": 32, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1363,7 +1372,7 @@ }, { "cell_type": "code", - "execution_count": 33, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1384,7 +1393,7 @@ }, { "cell_type": "code", - "execution_count": 34, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1394,7 +1403,7 @@ }, { "cell_type": "code", - "execution_count": 35, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1425,7 +1434,7 @@ }, { "cell_type": "code", - "execution_count": 36, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1442,7 +1451,7 @@ }, { "cell_type": "code", - "execution_count": 37, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1578,7 +1587,7 @@ }, { "cell_type": "code", - "execution_count": 38, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1648,7 +1657,7 @@ }, { "cell_type": "code", - "execution_count": 39, + "execution_count": null, "metadata": { "scrolled": false }, @@ -1859,7 +1868,7 @@ }, { "cell_type": "code", - "execution_count": 40, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1871,7 +1880,7 @@ }, { "cell_type": "code", - "execution_count": 41, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1883,7 +1892,7 @@ }, { "cell_type": "code", - "execution_count": 42, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1898,7 +1907,7 @@ }, { "cell_type": "code", - "execution_count": 43, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1907,7 +1916,7 @@ }, { "cell_type": "code", - "execution_count": 44, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1916,7 +1925,7 @@ }, { "cell_type": "code", - "execution_count": 45, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1925,7 +1934,7 @@ }, { "cell_type": "code", - "execution_count": 46, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -1941,21 +1950,11 @@ }, { "cell_type": "code", - "execution_count": 48, + "execution_count": null, "metadata": { "scrolled": true }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "WARNING:tensorflow:From C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\zfit\\core\\sample.py:163: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n", - "Instructions for updating:\n", - "Use tf.cast instead.\n" - ] - } - ], + "outputs": [], "source": [ "# zfit.run.numeric_checks = False \n", "\n", @@ -2015,7 +2014,7 @@ " \n", " if bo5:\n", " \n", - " if __ < 6:\n", + " if __ >= 6:\n", " \n", " while len(Nll_list[-1])/bo5_set < nr_of_toys:\n", "\n", @@ -2119,21 +2118,9 @@ }, { "cell_type": "code", - "execution_count": 49, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "(22, 1)\n", - "(22, 2)\n", - "(22, 3)\n", - "(22, 4)\n", - "bo1\n" - ] - } - ], + "outputs": [], "source": [ "if load:\n", " Nll_list = []\n", @@ -2157,25 +2144,31 @@ " with open(r\"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl\".format(_dir, job, mi,ma,ste), \"rb\") as input_file:\n", " _Nll_list = pkl.load(input_file)\n", " \n", + "# print(_Nll_list)\n", + " \n", " if bo5: \n", " for s in range(2*ste):\n", - " Nll_list[s].append(np.min(_Nll_list[s]))\n", + " if _Nll_list[s]: \n", + " Nll_list[s].append(np.min(_Nll_list[s]))\n", + " print(np.min(_Nll_list[s]))\n", + " else:\n", + " print('empty in {}'.format(s))\n", " else:\n", " for s in range(2*ste):\n", " Nll_list[s].extend(_Nll_list[s])\n", " \n", - " with open(r\"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl\".format(_dir, job, mi,ma,ste), \"rb\") as input_file:\n", - " _CLs_values = pkl.load(input_file)\n", + "# with open(r\"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl\".format(_dir, job, mi,ma,ste), \"rb\") as input_file:\n", + "# _CLs_values = pkl.load(input_file)\n", " \n", - " for s in range(ste):\n", - " CLs_values[s].extend(_CLs_values[s])\n", + "# for s in range(ste):\n", + "# CLs_values[s].extend(_CLs_values[s])\n", " \n", " print(np.shape(Nll_list))" ] }, { "cell_type": "code", - "execution_count": 50, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -2185,11 +2178,11 @@ "# for s in range(2*ste):\n", "# Nll_list[s] = [np.min(Nll_list[s])]\n", "\n", - "if bo5: \n", + "if bo5 and load: \n", " CLs_values= []\n", " for i in range(int(len(Nll_list)/2)):\n", " CLs_values.append([])\n", - " for j in range(len(Nll_list[0])):\n", + " for j in range(len(Nll_list[2*i])):\n", " CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j])\n", "\n", "\n", @@ -2202,12 +2195,12 @@ " with open(\"{}/{}-{}_{}s--CLs_Nll_list.pkl\".format(dirName, mi,ma,ste), \"wb\") as f:\n", " pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL)\n", " \n", - " CLs_values = []\n", + "# CLs_values = []\n", " \n", - " for i in range(int(len(Nll_list)/2)):\n", - " CLs_values.append([])\n", - " for j in range(nr_of_toys):\n", - " CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j])\n", + "# for i in range(int(len(Nll_list)/2)):\n", + "# CLs_values.append([])\n", + "# for j in range(nr_of_toys):\n", + "# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j])\n", "\n", " with open(\"{}/{}-{}_{}s--CLs_list.pkl\".format(dirName, mi,ma,ste), \"wb\") as f:\n", " pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL)" @@ -2215,7 +2208,7 @@ }, { "cell_type": "code", - "execution_count": 51, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -2232,22 +2225,9 @@ }, { "cell_type": "code", - "execution_count": 56, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAEICAYAAABPgw/pAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAdg0lEQVR4nO3dfXRV9Z3v8fe3PEWvUafCzBSiJmNBBdEoQeNSMFVU1PjQCgpoC1rJdVXuaGXNEscOUi619AG1Xmm9VC1eRwyWagUGH6ZWKq1SEzQgD5KC4hgjiEgZfAiKfu8f50APyQk5wNnZyf59Xmtlec7e+5zz2QKf/LKz92+buyMiIp3fl+IOICIi+aFCFxFJCBW6iEhCqNBFRBJChS4ikhAqdBGRhFChS5DMbIqZ/XvcOUTySYUu7cbMxphZrZl9aGbvmtlTZnZmel2LgjWzxWZ2XTxp88fMzjGz183sYzN73syOzuE1Z5mZm9m0jGU9zOwuM2s0s61m9nMz6xZteulMVOjSLszsZuBu4A7gH4CjgJ8Dl8aZK2pm1hN4HPg34MtALTC3jdd0A34G/LnZqklAGXAC0A84BfheniNLJ6ZCl8iZ2WHAVOAGd3/c3T9y98/cfYG7/4uZDQf+FbgyPXpfbmY/AIYA96aX3ZvlfZ82swnNli03s2+kH//MzN42s/82s2VmNqSVfBVm1tBs2QYzG5Z+/CUzm2Rm681si5k9ZmZfznH3vwGscvdfu3sTMAU4ycyO28trJgLPAq83W34xcI+7f+Dum4F7gGtzzCEBUKFLezgdKACeyLbS3Z8mNXKf6+6HuPtJ7n4bsASYkF42IctL5wCjdz0xs/7A0cB/pBfVAKWkRsZzgF+bWcF+5P9n4DLgLKA3sBWYmfG5K8xsTCuvHQAsz9jXj4D16eUtpA/HXEvqG2CL1emvzOdF6W+YIip0aRdHAO+7+848v+8TQGnGMemrgMfdfQeAu/+7u29x953uPgPoARy7H5/zP4Hb3L0h/d5TgBFm1jX9OSe6+5xWXnsIsK3Zsm1AYSvb3wP8m7t/mGXdU8CNZtbLzP6R1DcagINz3xVJMhW6tIctQM9dBZgv7r6d1Gh8VHrRKOCRXevNbKKZrTGzbWb2V+AwoOd+fNTRwBNm9tf0+6wBPif1u4C2fAgc2mzZocD25hua2cVAobu3doz9B8CrQB3wIvBb4DPgvVx2QpJPhS7t4SWgidRhi9Zkm/Yzl6lAHwVGm9npwEHA8wDp4+W3AFcAf+fuh5MaGVuW9/iIjFGumXUBemWsfxu4wN0Pz/gqcPd3csi3Cjgp473/B3BMenlz5wBlZrbRzDYCVwI3mdmTAO7+ibtPcPc+7v5PpL5RLnP3z3PIIQFQoUvk3H0bMBmYaWaXmdnBZtbNzC4wsx+nN9sEFJtZ5t/JTcA/tfH2i0iNoKeSOgb/RXp5IbAT2Ax0NbPJtBwp71IPFJjZRekzTL5H6vDMLvcBP9h1aCd9yCPXs3OeAE4ws8vTx+8nAyvcvfkvPCF1Jkw/Usf9S4H5wC+Ba9Kf28fMeltKeXr723PMIQFQoUu7cPc7gZtJleVmUqPeCaQOGwD8Ov3fLWb2Svrxz0gdq95qZve08r47SJ0WOIzULz53eYbUMed64C1SPyG83cp7bAO+A9wPvENqxJ551svPSJXrs2a2HVgKnLZrpZmtMrOrWnnvzcDlpA6XbE2/blTGa+8zs/vS22539427voBPgI/c/YP05seQOtTyEfAQMMndn832uRIm0w0uRESSQSN0EZGEUKGLiCSECl1EJCFU6CIiCZHXCz32Rc+ePb24uDiuj5dQNTZC795xpxDZb8uWLXvf3XtlWxdboRcXF1NbWxvXx0uoli2DQYPiTiGy38zsrdbW6ZCLhKWwtSlURDo/FbqEpbIy7gQikVGhS1jq6+NOIBKZ2I6hi8RiypTUl7Tw2Wef0dDQQFNTU9xRBCgoKKCoqIhu3XK/y6AKXUQAaGhooLCwkOLiYsyyTUop7cXd2bJlCw0NDZSUlOT8Oh1ykbBodN6qpqYmjjjiCJV5B2BmHHHEEfv801KbhW5mD5rZe2a2spX1Zmb3mNm69K24TtmnBCLtqV+/uBN0aCrzjmN//ixyGaHPBobvZf0FQN/0VxXwi31OIdJeFi6MO4FIZNo8hu7uL5hZ8V42uRT4f56ah3epmR1uZl9x93fzlFEkf7a3uPObtKJ40n+0vdE+2DD9oja32bhxIzfddBM1NTX06NGD4uJi7r77brp3786LL77ImDGpe3HX1dXR2NjIhRdemPV9Ro8ezapVq7jmmmvYunUrQ4cOZdiwYQeUf/Hixfz0pz9lYbNBQVtZWvPDH/6QBx54gC5dunDPPfdw/vnnH1A+yM8vRfuw540DGtLLWhS6mVWRGsVz1FFH5eGjgSkZNzyf0vxevNKRZBZELv+4I/msqqrU1aLNZfw9Km7a837P+5p1j88uGJPxGe3497MT/rtwd77+9a8zduxYqqurgVRZbtq0ic8//5w5c+bsUei1tbVZS3Tjxo28+OKLvPVWqxdU5tXesrRm9erVVFdXs2rVKhobGxk2bBj19fV06dLlgLLk45ei2Q70ZL1rhrvPcvcydy/r1SvrVAQi0cpW5tIhPP/883Tr1o3rr79+97LS0lKGDBnCpEmTWLJkCaWlpfzoRz9i8uTJzJ07l9LSUubO3fOe2ueddx7vvfcepaWlLFmyhHHjxjFv3jy2bdvGsccey9q1a4HUKP6Xv/wlAM8++yynn346p5xyCiNHjuTDDz8E4Omnn+a4447jzDPP5PHHH2+R+dNPP22R5YMPPuCyyy7jxBNPpLy8nBUrVrR43ZNPPsmoUaPo0aMHJSUlfPWrX+Xll18+4P+H+Sj0BuDIjOdFQGMe3lck/yZOjDuBtGLlypUMamWenenTpzNkyBDq6uq45ZZbmDp1KldeeSV1dXVceeWVe2w7f/58jjnmGOrq6hgyZMju5Ycddhj33nsv48aNo7q6mq1btzJ+/Hjef/99pk2bxu9+9zteeeUVysrKuPPOO2lqamL8+PEsWLCAJUuWsHHjxha5unfv3iLL7bffzsknn8yKFSu44447+Na3vtXide+88w5HHvm32iwqKuKdd3K55/je5aPQ5wPfyrhx7TYdP5cOSzMtBu3cc89l4MCB3HDDDdx///0ALF26lNWrV3PGGWdQWlrKQw89xFtvvcXrr79OSUkJffv2xcy4+uqrc/qMP/7xj3zzm98E4Oyzz2bLli1s27bnYa9st/7MxxlGbR5DN7NHgQqgp5k1kLrLeLd0qPtI3XX9QmAd8DHpO5SLdEgaoXdYAwYMYN68eZF+xhdffMGaNWs46KCD+OCDDygqKsLdOffcc3n00Uf32Laurm6/SjaXsi4qKuLtt//2q8eGhgZ652Gw0eYI3d1Hu/tX3L2buxe5+wPufl+6zPGUG9z9GHcf6O6aE1c6Lo3QO6yzzz6bHTt27D6uDVBTU8Mf/vAHCgsL2Z5xhlLz57m66667OP7443n00Ue59tpr+eyzzygvL+dPf/oT69atA+Djjz+mvr6e4447jjfffJP169cDtCj81rIMHTqURx55BEidGdOzZ08OPfTQPV5zySWXUF1dzY4dO3jzzTf5y1/+wqmnnrrP+9OcLv2XsGgO/pxFfSZSc2bGE088wU033cT06dMpKCjYfdpicXExXbt25aSTTmLcuHGMHTuW6dOnU1payq233triOHo29fX13H///bz88ssUFhYydOhQpk2bxve//31mz57N6NGj2bFjBwDTpk2jX79+zJo1i4suuoiePXty5plnsnJly+srv/a1r+2RZcqUKVxzzTWceOKJHHzwwTz00EMtXjNgwACuuOIK+vfvT9euXZk5c+YBn+ECYNl+PGgPZWVlnpcbXHTC07NC1SFOW1y8GCoqWr5Apy2yZs0ajj/++IgCyf7I9mdiZsvcvSzb9prLRcKiuVwkwVToEpbFi+NOIBIZFbqEpaoq7gQikVGhS1jKsh56FEkEFbqERSN0STAVuoSlsDDuBCKR0XnoEpZGTTOUs8xTH/Pyfm2fPhnF9LnLly+nsrKSESNG7HPk2bNnc9555+2+ivO6667j5ptvpn///vv8Xu1BI3QJi85y6bB2TZ9bUVHB+vXrWb16NXfccQebNm1iw4YNzJnzt+sD6urqWLRoUdb32TV97ooVK/jud797QJlmz55NY8Yg4P777++wZQ4qdAnNrFlxJ5BWRDV9bqbnnnuOk08+mYEDB3LttdfuvjJ06tSpDB48mBNOOIGqqircnXnz5lFbW8tVV11FaWkpn3zyCRUVFey6IPKQQw7htttu46STTqK8vJxNmzYBsH79esrLyxk8eDCTJ0/mkEMOifJ/2x5U6BKWBQviTiCtiHr63KamJsaNG8fcuXN57bXX2LlzJ7/4ReqOmRMmTKCmpoaVK1fyySefsHDhQkaMGEFZWRmPPPIIdXV1HHTQQXt8zkcffUR5eTnLly9n6NChu+egufHGG7nxxhupqanJy4Rb+0KFLmEZM6btbSSR1q5dS0lJCf3SNwofO3YsL7zwApD66eC0005j4MCB/P73v2fVqlVtvl/37t2prKwEYNCgQWzYsAGAl156iZEjRwLsPubfXlToEpb0P0DpeAYMGMCyCO8o1dq8VU1NTXznO99h3rx5vPbaa4wfP56mpqY2369bt267p8Xt0qULO3fuzGve/aFCl7BohN5hRT197nHHHceGDRt2T5P78MMPc9ZZZ+0u7549e/Lhhx/uMSf7/nxOeXk5v/nNbwB23xu1vei0RQmLGcQ0w2in086zl0Y9fW5BQQG/+tWvGDlyJDt37mTw4MFcf/319OjRg/HjxzNw4ECKi4sZPHjw7teMGzeO66+/noMOOoiXXnopp/24++67ufrqq5kxYwYXXXQRhx2W59M/90KFLmFRmXdovXv35rHHHsu67rnnntvjeU1NTdbtiouL95i3fPbs2bsfn3POObz66qstXjNt2jSmTZvWYvnll1/O5Zdfvvv54ozTXnfdSBpgxIgRu89z79OnD0uXLsXMqK6upqwdp5tQoUtY5szRYReJ1LJly5gwYQLuzuGHH86DDz7Ybp+tQpewLFyoQpdIDRkyhOXLl8fy2fqlqIRlzpy2twlYXHcwk5b2589ChS5hufjiuBN0WAUFBWzZskWl3gG4O1u2bKGgoGCfXqdDLhIWTZ/bqqKiIhoaGti8eXPcUYTUN9iioqJ9eo0KXcKS7QbRAqQulCkpKYk7hhwAHXKRsLTz3Boi7UmFLmHZx6v+RDoTFbqERdPnSoKp0CUs6bmsRZJIhS5h0QhdEkyFLmHRWS6SYCp0CcuUKXEnEImMCl3Ckr5bjUgSqdAlLO04lalIe8up0M1suJmtNbN1ZjYpy/qjzOx5M3vVzFaY2YX5jyqSB42NcScQiUybhW5mXYCZwAVAf2C0mfVvttn3gMfc/WRgFPDzfAcVyYsZM+JOIBKZXEbopwLr3P0Nd/8UqAYubbaNA4emHx8GaBgkHZNG6JJguRR6H+DtjOcN6WWZpgBXm1kDsAj4X9neyMyqzKzWzGo1o5vEQiN0SbBcCt2yLGs+YfJoYLa7FwEXAg+bWYv3dvdZ7l7m7mW9evXa97QiB2rQoLgTiEQml0JvAI7MeF5Ey0Mq3wYeA3D3l4ACoGc+Aorkla4UlQTLpdBrgL5mVmJm3Un90nN+s23+CzgHwMyOJ1XoOqYiHU9hYdwJRCLTZqG7+05gAvAMsIbU2SyrzGyqmV2S3mwiMN7MlgOPAuNc97GSjqiyMu4EIpHJ6Y5F7r6I1C87M5dNzni8Gjgjv9FEIlBfH3cCkcjoSlEJi+ZykQRToYuIJIQKXcKiEbokmApdwqLZFiXBVOgSloUL404gEhkVuoRl+/a4E4hERoUuYamqijuBSGRU6BKWZcviTiASGRW6hGXixLgTiERGhS5h6d077gQikVGhS1g0QpcEU6FLWDRClwRToUtYamvjTiASGRW6hEWzLUqCqdAlLJrLRRJMhS5hWbw47gQikVGhS1h0pagkmApdwlJWFncCkcio0CUsGqFLgqnQJSyFhXEnEImMCl3C0tgYdwKRyKjQJSw6y0USTIUuYZk1K+4EIpFRoUtYFiyIO4FIZFToEpYxY+JOIBIZFbqEpbIy7gQikVGhS1g0QpcEU6FLWMziTiASGRW6hMU97gQikVGhS1jmzIk7gUhkVOgSloUL404gEhkVuoRFI3RJsJwK3cyGm9laM1tnZpNa2eYKM1ttZqvMTP9qpGO6+OK4E4hEpmtbG5hZF2AmcC7QANSY2Xx3X52xTV/gVuAMd99qZn8fVWCRA6LpcyXBchmhnwqsc/c33P1ToBq4tNk244GZ7r4VwN3fy29MkTypqIg7gUhkcin0PsDbGc8b0ssy9QP6mdmfzGypmQ3PV0CRvOrdO+4EIpFp85ALkO1KjOYn83YF+gIVQBGwxMxOcPe/7vFGZlVAFcBRRx21z2FFDtj27XEnEIlMLiP0BuDIjOdFQPO7BDQAT7r7Z+7+JrCWVMHvwd1nuXuZu5f16tVrfzOL7D9NnysJlkuh1wB9zazEzLoDo4D5zbb5LfA1ADPrSeoQzBv5DCqSF7W1cScQiUybhe7uO4EJwDPAGuAxd19lZlPN7JL0Zs8AW8xsNfA88C/uviWq0CL7TSN0SbBcjqHj7ouARc2WTc547MDN6S+RjquiQrehk8TSlaISlilT4k4gEhkVuoSlX7+4E4hERoUuYSkrizuBSGRU6BKWxuZn3IokhwpdwjJjRtwJRCKjQpewaIQuCaZCl7BohC4JpkKXsAwaFHcCkcio0CUsulJUEkyFLmEpLIw7gUhkVOgSlsrKuBOIREaFLmGpr487gUhkVOgSFs3lIgmmQhcRSQgVuoRFI3RJMBW6hEWzLUqCqdAlLAsXxp1AJDIqdAnL9u1xJxCJjApdwlJVFXcCkcio0CUsy5bFnUAkMip0CcvEiXEnEImMCl3C0rt33AlEIqNCl7BohC4JpkKXsGiELgmmQpew1NbGnUAkMip0CYtmW5QEU6FLWDSXiySYCl3Csnhx3AlEIqNCl7DoSlFJMBW6hKWsLO4EIpFRoUtYNEKXBFOhS1gKC+NOIBIZFbqEpbEx7gQikcmp0M1suJmtNbN1ZjZpL9uNMDM3Mx2olI5JZ7lIgrVZ6GbWBZgJXAD0B0abWf8s2xUC/wz8Od8hRfJm1qy4E4hEJpcR+qnAOnd/w90/BaqBS7Ns97+BHwNNecwnkl8LFsSdQCQyuRR6H+DtjOcN6WW7mdnJwJHuvtcbNppZlZnVmlnt5s2b9zmsyAEbMybuBCKRyaXQLcsy373S7EvAXUCb85K6+yx3L3P3sl69euWeUiRfKivjTiASmVwKvQE4MuN5EZB5qkAhcAKw2Mw2AOXAfP1iVDokjdAlwXIp9Bqgr5mVmFl3YBQwf9dKd9/m7j3dvdjdi4GlwCXurnlKpeOxbD9wiiRDm4Xu7juBCcAzwBrgMXdfZWZTzeySqAOK5JV729uIdFJdc9nI3RcBi5otm9zKthUHHkskInPm6LCLJJauFJWwLNzriVginZoKXcIyZ07cCUQio0KXsFx8cdwJRCKjQpewaPpcSTAVuoSloiLuBCKRUaFLWHr3jjuBSGRU6BKW7dvjTiASGRW6hEXT50qCqdAlLLWakUKSS4UuYdEIXRJMhS5h0VkukmAqdAnLlClxJxCJjApdwtKvX9wJRCKjQpewlOm+K5JcKnQJS2Nj29uIdFIqdAnLjBlxJxCJjApdwqIRuiSYCl3CohG6JJgKXcIyaFDcCUQio0KXsOhKUUkwFbqEpbAw7gQikVGhS1gqK+NOIBIZFbqEpb4+7gQikVGhS1g0l4skmApdRCQhVOgSFo3QJcFU6BIWzbYoCaZCl7AsXBh3ApHIqNAlLNu3x51AJDIqdAlLVVXcCUQio0KXsCxbFncCkcio0CUsEyfGnUAkMjkVupkNN7O1ZrbOzCZlWX+zma02sxVm9pyZHZ3/qCJ50Lt33AlEItNmoZtZF2AmcAHQHxhtZv2bbfYqUObuJwLzgB/nO6hIXmiELgmWywj9VGCdu7/h7p8C1cClmRu4+/Pu/nH66VKgKL8xRfJEI3RJsFwKvQ/wdsbzhvSy1nwbeCrbCjOrMrNaM6vdvHlz7ilF8qW2Nu4EIpHJpdAtyzLPuqHZ1UAZ8JNs6919lruXuXtZr169ck8pki+abVESLJdCbwCOzHheBLS4066ZDQNuAy5x9x35iSeSZ5rLRRIsl0KvAfqaWYmZdQdGAfMzNzCzk4H/S6rM38t/TJE8Wbw47gQikWmz0N19JzABeAZYAzzm7qvMbKqZXZLe7CfAIcCvzazOzOa38nYi8dKVopJgXXPZyN0XAYuaLZuc8XhYnnOJRKOsLO4EIpHRlaISFo3QJcFU6BKWwsK4E4hERoUuYWlscYKWSGKo0CUsOstFEkyFLmGZNSvuBCKRUaFLWBYsiDuBSGRU6BKWMWPiTiASGRW6hKWyMu4EIpFRoUtYNEKXBFOhS1gs2+ShIsmgQpeweNaZn0USQYUuYZkzJ+4EIpFRoUtYFi6MO4FIZFToEhaN0CXBVOgSlosvjjuBSGRU6BIWTZ8rCaZCl7BUVMSdQCQyKnQJS+/ecScQiYwKXcKyfXvcCUQio0KXsGj6XEkwFbqEpbY27gQikVGhS1g0QpcEU6FLWHSWiySYCl3CMmVK3AlEIqNCl7D06xd3ApHIqNAlLGVlcScQiYwKXcLS2Bh3ApHIqNAlLDNmxJ1AJDIqdAmLRuiSYCp0CYtG6JJgKnQJy6BBcScQiYwKXcKiK0UlwVToEpbCwrgTiEQmp0I3s+FmttbM1pnZpCzre5jZ3PT6P5tZcb6DiuRFZWXcCUQi02ahm1kXYCZwAdAfGG1m/Ztt9m1gq7t/FbgL+FG+g4rkRX193AlEIpPLCP1UYJ27v+HunwLVwKXNtrkUeCj9eB5wjplZ/mKK5InmcpEEM3ff+wZmI4Dh7n5d+vk3gdPcfULGNivT2zSkn69Pb/N+s/eqAnbdpfdYYG2+dqQd9QTeb3OrZAltn0PbX9A+dyZHu3uvbCu65vDibCPt5t8FctkGd58FdOrTDMys1t2DmhAktH0ObX9B+5wUuRxyaQCOzHheBDS/3G73NmbWFTgM+CAfAUVEJDe5FHoN0NfMSsysOzAKmN9sm/nA2PTjEcDvva1jOSIikldtHnJx951mNgF4BugCPOjuq8xsKlDr7vOBB4CHzWwdqZH5qChDx6xTHzLaT6Htc2j7C9rnRGjzl6IiItI56EpREZGEUKGLiCSECj0HZvYTM3vdzFaY2RNmdnjGulvTUx6sNbPz48yZT2Y20sxWmdkXZlbWbF0i9xnanuYiCczsQTN7L339yK5lXzaz/zSzv6T/+3dxZsw3MzvSzJ43szXpv9c3ppcnar9V6Ln5T+AEdz8RqAduBUhPgTAKGAAMB36eniohCVYC3wBeyFyY5H3OcZqLJJhN6s8u0yTgOXfvCzyXfp4kO4GJ7n48UA7ckP6zTdR+q9Bz4O7PuvvO9NOlpM7Fh9SUB9XuvsPd3wTWkZoqodNz9zXunu1K3sTuM7lNc9HpufsLtLxOJHP6joeAy9o1VMTc/V13fyX9eDuwBuhDwvZbhb7vrgWeSj/uA7ydsa4hvSzJkrzPSd63tvyDu78LqfID/j7mPJFJzwZ7MvBnErbfuVz6HwQz+x3wj1lW3ebuT6a3uY3Uj26P7HpZlu07zXmguexztpdlWdZp9rkNSd43AczsEOA3wE3u/t9Jm0NQhZ7m7sP2tt7MxgKVwDkZV8HmMi1Ch9XWPreiU+9zG5K8b23ZZGZfcfd3zewrwHtxB8o3M+tGqswfcffH04sTtd865JIDMxsO3AJc4u4fZ6yaD4xK3+CjBOgLvBxHxnaU5H3OZZqLpMqcvmMs0NpPaJ1SejrvB4A17n5nxqpE7beuFM1BekqDHsCW9KKl7n59et1tpI6r7yT1Y9xT2d+lczGzrwP/B+gF/BWoc/fz0+sSuc8AZnYhcDd/m+biBzFHyjszexSoIDV97CbgduC3wGPAUcB/ASPdPTET7JnZmcAS4DXgi/TifyV1HD0x+61CFxFJCB1yERFJCBW6iEhCqNBFRBJChS4ikhAqdBGRhFChi4gkhApdRCQh/j/paS3vCad70QAAAABJRU5ErkJggg==\n", - "text/plain": [ - "
" - ] - }, - "metadata": { - "needs_background": "light" - }, - "output_type": "display_data" - } - ], + "outputs": [], "source": [ "l = []\n", "\n", @@ -2269,49 +2249,9 @@ }, { "cell_type": "code", - "execution_count": 57, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "BR: 0.0000\n", - "1.0\n", - "\n", - "BR: 0.0001\n", - "1.0\n", - "\n", - "BR: 0.0002\n", - "0.0\n", - "\n", - "BR: 0.0003\n", - "1.0\n", - "\n", - "BR: 0.0004\n", - "1.0\n", - "\n", - "BR: 0.0005\n", - "1.5\n", - "\n", - "BR: 0.0006\n", - "0.5\n", - "\n", - "BR: 0.0007\n", - "0.0\n", - "\n", - "BR: 0.0008\n", - "0.5\n", - "\n", - "BR: 0.0009\n", - "0.5\n", - "\n", - "BR: 0.0010\n", - "0.5\n", - "\n" - ] - } - ], + "outputs": [], "source": [ "for s in range(len(l)):\n", " print('BR: {:.4f}'.format(BR_steps[s]))\n", @@ -2325,7 +2265,8 @@ "metadata": {}, "outputs": [], "source": [ - "# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10]))" + "for i in range(len(Nll_list)):\n", + " print(np.mean(np.array(Nll_list[i])))" ] }, { diff --git a/__pycache__/pdg_const.cpython-37.pyc b/__pycache__/pdg_const.cpython-37.pyc index fbac169..86c4904 100644 --- a/__pycache__/pdg_const.cpython-37.pyc +++ b/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/2254881/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/2254881/__pycache__/helperfunctions.cpython-37.pyc deleted file mode 100644 index 9311452..0000000 --- a/data/CLs/finished/f1d1/2254881/__pycache__/helperfunctions.cpython-37.pyc +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254881/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/2254881/__pycache__/pdg_const.cpython-37.pyc deleted file mode 100644 index 725153c..0000000 --- a/data/CLs/finished/f1d1/2254881/__pycache__/pdg_const.cpython-37.pyc +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254881/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/2254881/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl deleted file mode 100644 index 69f9229..0000000 --- a/data/CLs/finished/f1d1/2254881/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254881/data/CLs/0.0-0.001_11s--CLs_list.pkl b/data/CLs/finished/f1d1/2254881/data/CLs/0.0-0.001_11s--CLs_list.pkl deleted file mode 100644 index 1e18f87..0000000 --- a/data/CLs/finished/f1d1/2254881/data/CLs/0.0-0.001_11s--CLs_list.pkl +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254881/helperfunctions.py b/data/CLs/finished/f1d1/2254881/helperfunctions.py deleted file mode 100644 index 88e120f..0000000 --- a/data/CLs/finished/f1d1/2254881/helperfunctions.py +++ /dev/null @@ -1,33 +0,0 @@ -# some helperfunctions - -import matplotlib -matplotlib.use("agg") -import matplotlib.pyplot as plt - -#Dislpay time (e.g. while generating points) - -display_intervals = ( - ('w', 604800), # 60 * 60 * 24 * 7 - ('d', 86400), # 60 * 60 * 24 - ('h', 3600), # 60 * 60 - ('min', 60), - ('s', 1), - ) - -def display_time(seconds, granularity=2): - result = [] - - for name, count in display_intervals: - value = seconds // count - if value: - seconds -= value * count - if value == 1: - name = name.rstrip('s') - result.append("{} {}".format(value, name)) - return ', '.join(result[:granularity]) - -def prepare_plot(title): - plt.title(title) - plt.grid() - plt.legend(loc = 'best') - plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/2254881/pdg_const.py b/data/CLs/finished/f1d1/2254881/pdg_const.py deleted file mode 100644 index 6645dd7..0000000 --- a/data/CLs/finished/f1d1/2254881/pdg_const.py +++ /dev/null @@ -1,226 +0,0 @@ -pdg = { - - - ###Particle masses### - - "mbstar" : 5415.4, - "mbstar0" : 5711.0, - "B0_M" : 5279.5, - "Bs_M" : 5366.7, - "Bplus_M" : 5279.3, - "Lb_M" : 5619.4, - "D0_M" : 1864.8, - "Dst_M" : 2010, - "pi_M" : 139.6, - "Jpsi_M" : 3096.9, - "Psi2s_M" : 3685.6, - "kaon_M" : 493.7, - "Ks_M" : 497.6, - "phi_M" : 1019.5, - "rho_M" : 775.26, - "rho_width" : 149.1, - "omega_M" : 782.65, - "omega_width" : 8.49, - - "muon_M" : 105.7, - "tau_M": 1776.86, - - "squark_M" : 95.0, - "bquark_M" : 4180.0, - "cquark_M" : 1275.0, - - "Bplus_tau" : 1.638e-12, - - ###Wilson coefficients### - - "C1" : -0.257, - "C2" : 1.009, - "C3" : -0.005, - "C4" : -0.078, - - "C7eff" : -0.306, - "C9eff" : 4.211, - "C10eff" : -4.103, - -# "C7eff": 0.0, -# "C9eff": 0.0, -# "C10eff": 0.0, - - ###Other constants - - "GF" : 1.1663787e-5, - "alpha_ew" : 1.0/137.0, - "Vts" : 0.0394, - "Vtb" : 1.019, - "number_of_decays": 5404696, - - #Formfactor z coefficients - - #"b0" : [0.285, 0.19, -0.17], - #"bplus" : [0.437, -1.41, -2.5], - #"bT" : [0.440, -1.47, -2.7] - - "b0" : [0.292, 0.281, 0.150], - "bplus" : [0.466, -0.885, -0.213], - "bT" : [0.460, -1.089, -1.114], - - "NR_BR": 4.37e-7, - "NR_auc": 0.00133, - - #Resonances format(mass, width, phase, scale) - - # pre scaling - -# "rho": (775.26, 149.0, -0.35, 1.0), - -# "omega": (782.7, 8.5, 0.26, 1.0), - -# "phi": (1019.46, 4.25, 0.5, 1.0), - -# "jpsi": (3096.0, 0.09, -1.5, 2e-2), -# "jpsi_auc": 0.2126825758464027, - -# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), -# "psi2s_auc": 2.802257483178487e-10, - -# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), - -# "p4040": (4039.0, 80.0, -2.52, 2.0), - -# "p4160": (4191.0, 70.0, -1.9, 2.2), - -# "p4415": (4421.0, 62.0, -2.52, 1.0), - - - # after scaling (Phase combination --) - - -# "rho": (743.2, 149.0, -0.22, 1.05), - -# "omega": (782.7, 8.5, 0.38, 6.8), - -# "phi": (1013.5, 4.25, 0.62, 19.2), - -# "jpsi": (3096.1, 0.09, 1.63, 9897.0), -# "jpsi_auc": 0.2126825758464027, -# "jpsi_phase_unc": 0.05, - -# "psi2s": (3686.0, 0.3, 1.8, 1396.0), -# "psi2s_auc": 0.0151332263, -# "psi2s_phase_unc": 0.1, - -# "p3770": (3773.0, 27.2, -2.95, 2.5), - -# "p4040": (4039.0, 80.0, -2.75, 1.01), - -# "p4160": (4191.0, 70.0, -2.28, 2.2), - -# "p4415": (4421.0, 62.0, -2.31, 1.24), - - # Phase combination of paper ++ - -# "rho": (743.2, 149.0, -0.35, 1.05), - -# "omega": (782.7, 8.5, 0.26, 6.8), - -# "phi": (1013.5, 4.25, 0.47, 19.2), - -# "jpsi": (3096.1, 0.09, -1.66, 9897.0), -# "jpsi_auc": 0.2126825758464027, -# "jpsi_phase_unc": 0.05, - -# "psi2s": (3686.0, 0.3, -1.93, 1396.0), -# "psi2s_auc": 0.0151332263, -# "psi2s_phase_unc": 0.1, - -# "p3770": (3773.0, 27.2, -2.13, 2.5), - -# "p4040": (4039.0, 80.0, -2.52, 1.01), - -# "p4160": (4191.0, 70.0, -1.90, 2.2), - -# "p4415": (4421.0, 62.0, -2.52, 1.24), - - # Phase combination of paper +- - - # "rho": (743.2, 149.0, -0.26, 1.05), - # - # "omega": (782.7, 8.5, 0.35, 6.8), - # - # "phi": (1013.5, 4.25, 0.58, 19.2), - # - # "jpsi": (3096.1, 0.09, 1.47, 9897.0), - # "jpsi_auc": 0.2126825758464027, - # "jpsi_phase_unc": 0.05, - # - # "psi2s": (3686.0, 0.3, -2.21, 1396.0), - # "psi2s_auc": 0.0151332263, - # "psi2s_phase_unc": 0.1, - # - # "p3770": (3773.0, 27.2, -2.140, 2.5), - # - # "p4040": (4039.0, 80.0, -2.64, 1.01), - # - # "p4160": (4191.0, 70.0, -2.11, 2.2), - # - # "p4415": (4421.0, 62.0, -2.42, 1.24), - - # Phase combination of paper -+ - - "rho": (743.2, 149.0, -0.30, 1.05), - - "omega": (782.7, 8.5, 0.30, 6.8), - - "phi": (1013.5, 4.25, 0.51, 19.2), - - "jpsi": (3096.1, 0.09, -1.5, 9897.0), - "jpsi_auc": 0.2126825758464027, - "jpsi_phase_unc": 0.05, - - "psi2s": (3686.0, 0.3, 2.08, 1396.0), - "psi2s_auc": 0.0151332263, - "psi2s_phase_unc": 0.1, - - "p3770": (3773.0, 27.2, -2.89, 2.5), - - "p4040": (4039.0, 80.0, -2.69, 1.01), - - "p4160": (4191.0, 70.0, -2.13, 2.2), - - "p4415": (4421.0, 62.0, -2.43, 1.24), - - - # zeroing resonances - -# "rho": (775.26, 149.0, -0.35, 0.0), -# "omega": (782.7, 8.5, 0.26, 0.0), -# "phi": (1019.46, 4.25, 0.5, 0.0), -# "jpsi": (3096.0, 0.09, -1.5, 0.0), -# "psi2s": (3686.0, 0.3, -1.5, 0.0), -# "p3770": (3773.0, 27.2, -2.13, 0.0), -# "p4040": (4039.0, 80.0, -2.52, 0.0), -# "p4160": (4147.0, 22.0, -1.9, 0.0), -# "p4415": (4421.0, 62.0, -2.52, 0.0), - - # 2P contributions format(mass, amp, phase) - -# "D_bar": ( - - #general - - "rho_BR": 1.7e-10, - "omega_BR": 4.9e-10, - "phi_BR": 2.5e-9, - "jpsi_BR": 6.02e-5, - "psi2s_BR": 4.97e-6, - "p3770_BR": 1.38e-9, - "p4040_BR": 4.2e-10, - "p4160_BR": 2.6e-9, - "p4415_BR": 6.1e-10, - -# Estimates - "Dbar_scale": 1.46, #with phase = pi - - "DDstar_scale": 2.41, #with phase = pi - - } diff --git a/data/CLs/finished/f1d1/2254881/raremodel-nb1.py b/data/CLs/finished/f1d1/2254881/raremodel-nb1.py deleted file mode 100644 index 1a5d9be..0000000 --- a/data/CLs/finished/f1d1/2254881/raremodel-nb1.py +++ /dev/null @@ -1,1939 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -# # Import - -# In[1]: - - -import os - -# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" - -import numpy as np -from pdg_const import pdg -import matplotlib -import matplotlib.pyplot as plt -import pickle as pkl -import sys -import time -from helperfunctions import display_time, prepare_plot -import cmath as c -import scipy.integrate as integrate -from scipy.optimize import fminbound -from array import array as arr -import collections -from itertools import compress -import tensorflow as tf -import zfit -from zfit import ztf -# from IPython.display import clear_output -import os -import tensorflow_probability as tfp -tfd = tfp.distributions - - -# In[2]: - - -# chunksize = 10000 -# zfit.run.chunking.active = True -# zfit.run.chunking.max_n_points = chunksize - - -# # Build model and graphs -# ## Create graphs - -# In[ ]: - - - - - -# In[3]: - - -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 - #check if subscript is viable - - if subscript != "0" and subscript != "+" and subscript != "T": - raise ValueError('Wrong subscript entered, choose either 0, + or T') - - #get constants - - mK = ztf.constant(pdg['Ks_M']) - mbstar0 = ztf.constant(pdg["mbstar0"]) - mbstar = ztf.constant(pdg["mbstar"]) - - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mB = ztf.constant(pdg['Bplus_M']) - - #N comes from derivation in paper - - N = 3 - - #some helperfunctions - - tpos = (mB - mK)**2 - tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 - - z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) - z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) - z = tf.divide(z_oben, z_unten) - - #calculate f0 - - if subscript == "0": - prefactor = 1/(1 - q2/(mbstar0**2)) - _sum = 0 - b0 = [b0_0, b0_1, b0_2] - - for i in range(N): - _sum += b0[i]*(tf.pow(z,i)) - - return ztf.to_complex(prefactor * _sum) - - #calculate f+ or fT - - else: - prefactor = 1/(1 - q2/(mbstar**2)) - _sum = 0 - - if subscript == "T": - bT = [bT_0, bT_1, bT_2] - for i in range(N): - _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) - else: - bplus = [bplus_0, bplus_1, bplus_2] - for i in range(N): - _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) - - return ztf.to_complex(prefactor * _sum) - -def resonance(q, _mass, width, phase, scale): - - q2 = tf.pow(q, 2) - - mmu = ztf.constant(pdg['muon_M']) - - p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) - - p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) - - gamma_j = tf.divide(p, q) * _mass * width / p0 - - #Calculate the resonance - - _top = tf.complex(_mass * width, ztf.constant(0.0)) - - _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) - - com = _top/_bottom - - #Rotate by the phase - - r = ztf.to_complex(scale*tf.abs(com)) - - _phase = tf.angle(com) - - _phase += phase - - com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) - - return com - - -def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): - - GF = ztf.constant(pdg['GF']) - alpha_ew = ztf.constant(pdg['alpha_ew']) - Vtb = ztf.constant(pdg['Vtb']) - Vts = ztf.constant(pdg['Vts']) - C10eff = ztf.constant(pdg['C10eff']) - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mK = ztf.constant(pdg['Ks_M']) - mB = ztf.constant(pdg['Bplus_M']) - - q2 = tf.pow(q, 2) - - #Some helperfunctions - - beta = 1. - 4. * mmu**2. / q2 - - 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.) - - #prefactor in front of whole bracket - - prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) - - #left term in bracket - - 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) - - #middle term in bracket - - _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) - - _under = q2 * mB**2. - - 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) - - #Note sqrt(q2) comes from derivation as we use q2 and plot q - - return prefactor1 * (bracket_left + bracket_middle) * 2 * q - -def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): - - q2 = tf.pow(q, 2) - - GF = ztf.constant(pdg['GF']) - alpha_ew = ztf.constant(pdg['alpha_ew']) - Vtb = ztf.constant(pdg['Vtb']) - Vts = ztf.constant(pdg['Vts']) - C7eff = ztf.constant(pdg['C7eff']) - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mK = ztf.constant(pdg['Ks_M']) - mB = ztf.constant(pdg['Bplus_M']) - - #Some helperfunctions - - beta = 1. - 4. * mmu**2. / q2 - - 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) - - #prefactor in front of whole bracket - - prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) - - #right term in bracket - - prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) - - 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) - - bracket_right = prefactor2 * abs_bracket - - #Note sqrt(q2) comes from derivation as we use q2 and plot q - - return prefactor1 * bracket_right * 2 * q - -def c9eff(q, funcs): - - C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) - - c9 = C9eff_nr + funcs - - return c9 - - -# In[4]: - - -def G(y): - - def inner_rect_bracket(q): - return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) - - def inner_right(q): - return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) - - big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) - - return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket - -def h_S(m, q): - - 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))) - -def h_P(m, q): - - 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) - -def two_p_ccbar(mD, m_D_bar, m_D_star, q): - - - #Load constants - nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) - nu_D = ztf.to_complex(pdg["nu_D"]) - nu_D_star = ztf.to_complex(pdg["nu_D_star"]) - - phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) - phase_D = ztf.to_complex(pdg["phase_D"]) - phase_D_star = ztf.to_complex(pdg["phase_D_star"]) - - #Calculation - left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) - - right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) - - right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) - - return left_part + right_part_D + right_part_D_star - - -# ## Build pdf - -# In[5]: - - -class total_pdf_cut(zfit.pdf.ZPDF): - _N_OBS = 1 # dimension, can be omitted - _PARAMS = ['b0_0', 'b0_1', 'b0_2', - 'bplus_0', 'bplus_1', 'bplus_2', - 'bT_0', 'bT_1', 'bT_2', - 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', - 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', - 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', - 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', - 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', - 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', - 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', - 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', - 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', - 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', - 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', - 'tau_mass', 'C_tt'] -# the name of the parameters - - def _unnormalized_pdf(self, x): - - x = x.unstack_x() - - b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] - bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] - bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] - - def rho_res(q): - return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], - phase = self.params['rho_phase'], width = self.params['rho_width']) - - def omega_res(q): - return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], - phase = self.params['omega_phase'], width = self.params['omega_width']) - - def phi_res(q): - return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], - phase = self.params['phi_phase'], width = self.params['phi_width']) - - def jpsi_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], - scale = self.params['jpsi_scale'], - phase = self.params['jpsi_phase'], - width = self.params['jpsi_width']) - def psi2s_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], - scale = self.params['psi2s_scale'], - phase = self.params['psi2s_phase'], - width = self.params['psi2s_width']) - def p3770_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], - scale = self.params['p3770_scale'], - phase = self.params['p3770_phase'], - width = self.params['p3770_width']) - - def p4040_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], - scale = self.params['p4040_scale'], - phase = self.params['p4040_phase'], - width = self.params['p4040_width']) - - def p4160_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], - scale = self.params['p4160_scale'], - phase = self.params['p4160_phase'], - width = self.params['p4160_width']) - - def p4415_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], - scale = self.params['p4415_scale'], - phase = self.params['p4415_phase'], - width = self.params['p4415_width']) - - def P2_D(q): - 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)) - 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))) - return Dbar_contrib + DDstar_contrib - - def ttau_cusp(q): - 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))) - - - 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) - - vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - tot = vec_f + axiv_nr - - #Cut out jpsi and psi2s - - tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) - - tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) - - return tot - -class total_pdf_full(zfit.pdf.ZPDF): - _N_OBS = 1 # dimension, can be omitted - _PARAMS = ['b0_0', 'b0_1', 'b0_2', - 'bplus_0', 'bplus_1', 'bplus_2', - 'bT_0', 'bT_1', 'bT_2', - 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', - 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', - 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', - 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', - 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', - 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', - 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', - 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', - 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', - 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', - 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', - 'tau_mass', 'C_tt'] -# the name of the parameters - - def _unnormalized_pdf(self, x): - - x = x.unstack_x() - - b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] - bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] - bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] - - def rho_res(q): - return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], - phase = self.params['rho_phase'], width = self.params['rho_width']) - - def omega_res(q): - return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], - phase = self.params['omega_phase'], width = self.params['omega_width']) - - def phi_res(q): - return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], - phase = self.params['phi_phase'], width = self.params['phi_width']) - - def jpsi_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], - scale = self.params['jpsi_scale'], - phase = self.params['jpsi_phase'], - width = self.params['jpsi_width']) - def psi2s_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], - scale = self.params['psi2s_scale'], - phase = self.params['psi2s_phase'], - width = self.params['psi2s_width']) - def p3770_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], - scale = self.params['p3770_scale'], - phase = self.params['p3770_phase'], - width = self.params['p3770_width']) - - def p4040_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], - scale = self.params['p4040_scale'], - phase = self.params['p4040_phase'], - width = self.params['p4040_width']) - - def p4160_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], - scale = self.params['p4160_scale'], - phase = self.params['p4160_phase'], - width = self.params['p4160_width']) - - def p4415_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], - scale = self.params['p4415_scale'], - phase = self.params['p4415_phase'], - width = self.params['p4415_width']) - - def P2_D(q): - 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)) - 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))) - return Dbar_contrib + DDstar_contrib - - def ttau_cusp(q): - 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))) - - - 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) - - vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - tot = vec_f + axiv_nr - - #Cut out jpsi and psi2s - -# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) - -# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) - - return tot - - -# ## Setup parameters - -# In[6]: - - -# formfactors - -b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) - -bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) -bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) -bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) - -bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) - - -#rho - -rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] - -rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) -rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) -rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#omega - -omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] - -omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) -omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) -omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - - -#phi - -phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] - -phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) -phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) -phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#jpsi - -jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] - -jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) -jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) -jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi2s - -psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] - -psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) -psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) -psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(3770) - -p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] - -p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) -p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) -p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4040) - -p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] - -p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) -p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) -p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4160) - -p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] - -p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) -p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) -p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4415) - -p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] - -p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) -p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) -p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - - -# ## Dynamic generation of 2 particle contribution - -# In[7]: - - -m_c = 1300 - -Dbar_phase = 0.0 -DDstar_phase = 0.0 -Dstar_mass = pdg['Dst_M'] -Dbar_mass = pdg['D0_M'] -D_mass = pdg['D0_M'] - -Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) -Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) -Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) -DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) -Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) -D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) -DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) - - -# ## Tau parameters - -# In[8]: - - -tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) -Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) - - -# ## Load data - -# In[9]: - - -x_min = 2*pdg['muon_M'] -x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) - -# # Full spectrum - -obs_toy = zfit.Space('q', limits = (x_min, x_max)) - -# Jpsi and Psi2s cut out - -obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) -obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) -obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) - -obs_fit = obs1 + obs2 + obs3 - -# 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: -# part_set = pkl.load(input_file) - -# x_part = part_set['x_part'] - -# x_part = x_part.astype('float64') - -# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) - - -# ## Setup pdf - -# In[10]: - - -total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, - psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, - p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, - p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, - p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, - p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, - rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, - omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, - phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, - Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, - Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, - tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, - bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, - bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) - -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, - psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, - p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, - p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, - p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, - p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, - rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, - omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, - phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, - Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, - Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, - tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, - bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, - bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) - -# print(total_pdf.obs) - -# print(calcs_test) - -# for param in total_f.get_dependents(): -# print(zfit.run(param)) - - -# In[11]: - - -total_f_fit.normalization(obs_toy) - - -# ## Test if graphs actually work and compute values - -# In[12]: - - -# def total_test_tf(xq): - -# def jpsi_res(q): -# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) - -# def psi2s_res(q): -# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) - -# def cusp(q): -# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) - -# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) - -# vec_f = vec(xq, funcs) - -# axiv_nr = axiv_nonres(xq) - -# tot = vec_f + axiv_nr - -# return tot - -# def jpsi_res(q): -# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) - -# calcs = zfit.run(total_test_tf(x_part)) - -test_q = np.linspace(x_min, x_max, int(2e6)) - -probs = total_f_fit.pdf(test_q, norm_range=False) - -calcs_test = zfit.run(probs) -# res_y = zfit.run(jpsi_res(test_q)) -# b0 = [b0_0, b0_1, b0_2] -# bplus = [bplus_0, bplus_1, bplus_2] -# bT = [bT_0, bT_1, bT_2] -# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) -# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) -# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) - - -# In[13]: - - -plt.clf() -# plt.plot(x_part, calcs, '.') -plt.plot(test_q, calcs_test, label = 'pdf') -# plt.plot(test_q, f0_y, label = '0') -# plt.plot(test_q, fT_y, label = 'T') -# plt.plot(test_q, fplus_y, label = '+') -# plt.plot(test_q, res_y, label = 'res') -plt.legend() -plt.ylim(0.0, 1.5e-6) -# plt.yscale('log') -# plt.xlim(770, 785) -plt.savefig('test.png') -# print(jpsi_width) - - -# In[14]: - - - - -# probs = mixture.prob(test_q) -# probs_np = zfit.run(probs) -# probs_np *= np.max(calcs_test) / np.max(probs_np) -# plt.figure() -# plt.semilogy(test_q, probs_np,label="importance sampling") -# plt.semilogy(test_q, calcs_test, label = 'pdf') - - -# In[15]: - - -# 0.213/(0.00133+0.213+0.015) - - -# ## Adjust scaling of different parts - -# In[16]: - - -total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) -# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) -# inte_fl = zfit.run(inte) -# print(inte_fl/4500) -# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) - - -# In[17]: - - -# # print("jpsi:", inte_fl) -# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - -# # print("psi2s:", inte_fl) -# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - -# name = "phi" - -# print(name+":", inte_fl) -# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - - -# print(x_min) -# print(x_max) -# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) -# total_f.update_integration_options(mc_sampler=lambda dim, num_results, -# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), -# draws_per_dim=1000000) -# # _ = [] - -# # for i in range(10): - -# # inte = total_f.integrate(limits = (x_min, x_max)) -# # inte_fl = zfit.run(inte) -# # print(inte_fl) -# # _.append(inte_fl) - -# # print("mean:", np.mean(_)) - -# _ = time.time() - -# inte = total_f.integrate(limits = (x_min, x_max)) -# inte_fl = zfit.run(inte) -# print(inte_fl) -# print("Time taken: {}".format(display_time(int(time.time() - _)))) - -# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) -# print(0.25**2*4.2/1000) - - -# # Sampling -# ## Mixture distribution for sampling - -# In[18]: - - - - -# print(list_of_borders[:9]) -# print(list_of_borders[-9:]) - - -class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): - def __call__(self, limits, dtype, n_to_produce): - # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) - low, high = limits.limit1d - low = tf.cast(low, dtype=dtype) - high = tf.cast(high, dtype=dtype) -# uniform = tfd.Uniform(low=low, high=high) -# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) -# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) - -# list_of_borders = [] -# _p = [] -# splits = 10 - -# _ = np.linspace(x_min, x_max, splits) - -# for i in range(splits): -# list_of_borders.append(tf.constant(_[i], dtype=dtype)) -# _p.append(tf.constant(1/splits, dtype=dtype)) - -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), -# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], -# high=list_of_borders[-(splits-1):])) - mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), - tf.constant(0.93, dtype=dtype), - tf.constant(0.05, dtype=dtype), - tf.constant(0.065, dtype=dtype), - tf.constant(0.04, dtype=dtype), - tf.constant(0.05, dtype=dtype)]), - components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), - tf.constant(3090, dtype=dtype), - tf.constant(3681, dtype=dtype), - tf.constant(3070, dtype=dtype), - tf.constant(1000, dtype=dtype), - tf.constant(3660, dtype=dtype)], - high=[tf.constant(x_max, dtype=dtype), - tf.constant(3102, dtype=dtype), - tf.constant(3691, dtype=dtype), - tf.constant(3110, dtype=dtype), - tf.constant(1040, dtype=dtype), - tf.constant(3710, dtype=dtype)])) -# dtype = tf.float64 -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), -# tf.constant(0.90, dtype=dtype), -# tf.constant(0.02, dtype=dtype), -# tf.constant(0.07, dtype=dtype), -# tf.constant(0.02, dtype=dtype)]), -# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), -# tf.constant(3089, dtype=dtype), -# tf.constant(3103, dtype=dtype), -# tf.constant(3681, dtype=dtype), -# tf.constant(3691, dtype=dtype)], -# high=[tf.constant(3089, dtype=dtype), -# tf.constant(3103, dtype=dtype), -# tf.constant(3681, dtype=dtype), -# tf.constant(3691, dtype=dtype), -# tf.constant(x_max, dtype=dtype)])) -# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) -# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) - sample = mixture.sample((n_to_produce, 1)) -# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) - weights = mixture.prob(sample)[:,0] -# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) - # sample = tf.expand_dims(sample, axis=-1) -# print(sample, weights) - -# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) - weights_max = None - thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) - return sample, thresholds, weights, weights_max, n_to_produce - - -# In[19]: - - -# total_f._sample_and_weights = UniformSampleAndWeights - - -# In[20]: - - -# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) - - -# In[21]: - - -# zfit.settings.set_verbosity(10) - - -# In[22]: - - -# # zfit.run.numeric_checks = False - -# nr_of_toys = 1 -# nevents = int(pdg["number_of_decays"]) -# nevents = pdg["number_of_decays"] -# event_stack = 1000000 -# # zfit.settings.set_verbosity(10) -# calls = int(nevents/event_stack + 1) - -# total_samp = [] - -# start = time.time() - -# sampler = total_f.create_sampler(n=event_stack) - -# for toy in range(nr_of_toys): - -# dirName = 'data/zfit_toys/toy_{0}'.format(toy) - -# if not os.path.exists(dirName): -# os.mkdir(dirName) -# print("Directory " , dirName , " Created ") - -# for call in range(calls): - -# sampler.resample(n=event_stack) -# s = sampler.unstack_x() -# sam = zfit.run(s) -# # clear_output(wait=True) - -# c = call + 1 - -# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) - -# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: -# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) - - -# In[23]: - - -# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: -# sam = pkl.load(input_file) -# print(sam[:10]) - -# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: -# sam2 = pkl.load(input_file) -# print(sam2[:10]) - -# print(np.sum(sam-sam2)) - - -# In[24]: - - -# print("Time to generate full toy: {} s".format(int(time.time()-start))) - -# total_samp = [] - -# for call in range(calls): -# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: -# sam = pkl.load(input_file) -# total_samp = np.append(total_samp, sam) - -# total_samp = total_samp.astype('float64') - -# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) - -# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) - -# print(total_samp[:nevents].shape) - - -# In[25]: - - -# plt.clf() - -# bins = int((x_max-x_min)/7) - -# # calcs = zfit.run(total_test_tf(samp)) -# print(total_samp[:nevents].shape) - -# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') -# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') - -# # plt.plot(sam, calcs, '.') -# # plt.plot(test_q, calcs_test) -# # plt.yscale('log') -# plt.ylim(0, 200) -# # plt.xlim(3080, 3110) - -# plt.legend() - -# plt.savefig('test2.png') - - -# In[26]: - - -# sampler = total_f.create_sampler(n=nevents) -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) - -# # for param in pdf.get_dependents(): -# # param.set_value(initial_value) - -# sampler.resample(n=nevents) - -# # Randomise initial values -# # for param in pdf.get_dependents(): -# # param.set_value(random value here) - -# # Minimise the NLL -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) -# minimum = minimizer.minimize(nll) - - -# In[27]: - - -# jpsi_width - - -# In[28]: - - -# plt.hist(sample, weights=1 / prob(sample)) - - -# # Fitting - -# In[29]: - - -# start = time.time() - -# for param in total_f.get_dependents(): -# param.randomize() - -# # for param in total_f.get_dependents(): -# # print(zfit.run(param)) - -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# # param_errors = result.error() - -# # for var, errors in param_errors.items(): -# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) - -# print("Function minimum:", result.fmin) -# # print("Results:", result.params) -# print("Hesse errors:", result.hesse()) - - -# In[30]: - - -# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) - -# # probs = total_f.pdf(test_q) - -# calcs_test = zfit.run(probs) -# res_y = zfit.run(jpsi_res(test_q)) - - -# In[31]: - - -# plt.clf() -# # plt.plot(x_part, calcs, '.') -# plt.plot(test_q, calcs_test, label = 'pdf') -# # plt.plot(test_q, res_y, label = 'res') -# plt.legend() -# plt.ylim(0.0, 10e-6) -# # plt.yscale('log') -# # plt.xlim(3080, 3110) -# plt.savefig('test3.png') -# # print(jpsi_width) - - -# In[32]: - - -# _tot = 4.37e-7+6.02e-5+4.97e-6 -# _probs = [] -# _probs.append(6.02e-5/_tot) -# _probs.append(4.97e-6/_tot) -# _probs.append(4.37e-7/_tot) -# print(_probs) - - -# In[33]: - - -# dtype = 'float64' -# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), -# tf.constant(0.917, dtype=dtype), -# tf.constant(0.076, dtype=dtype)]), -# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), -# tf.constant(3080, dtype=dtype), -# tf.constant(3670, dtype=dtype)], -# high=[tf.constant(x_max, dtype=dtype), -# tf.constant(3112, dtype=dtype), -# tf.constant(3702, dtype=dtype)])) -# # for i in range(10): -# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) - - -# In[34]: - - -# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) -# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) - - -# In[35]: - - -# def jpsi_res(q): -# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, -# phase = jpsi_phase, width = jpsi_width) - -# def psi2s_res(q): -# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, -# phase = psi2s_phase, width = psi2s_width) - -# def p3770_res(q): -# return resonance(q, _mass = p3770_mass, scale = p3770_scale, -# phase = p3770_phase, width = p3770_width) - -# def p4040_res(q): -# return resonance(q, _mass = p4040_mass, scale = p4040_scale, -# phase = p4040_phase, width = p4040_width) - -# def p4160_res(q): -# return resonance(q, _mass = p4160_mass, scale = p4160_scale, -# phase = p4160_phase, width = p4160_width) - -# def p4415_res(q): -# return resonance(q, _mass = p4415_mass, scale = p4415_scale, -# phase = p4415_phase, width = p4415_width) - - -# In[36]: - - -# 0.15**2*4.2/1000 -# result.hesse() - - -# ## Constraints - -# In[37]: - - -# 1. Constraint - Real part of sum of Psi contrib and D contribs - -sum_list = [] - -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)))) -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)))) -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)))) -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)))) -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)))) -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)))) -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))))) -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)))) - -sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) - -for part in sum_list: - sum_ru_1 += part - -sum_1 = tf.math.real(sum_ru_1) -# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), -# sigma = ztf.constant(2.2*10**-8)) - -constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) - -# 2. Constraint - Abs. of sum of Psi contribs and D contribs - -sum_2 = tf.abs(sum_ru_1) -constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) - -# 3. Constraint - Maximum eta of D contribs - -constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) - -constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) - -# 4. Constraint - Formfactor multivariant gaussian covariance fplus - -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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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.)]] - -def triGauss(val1,val2,val3,m = Cov_matrix): - - mean1 = ztf.constant(0.466) - mean2 = ztf.constant(-0.885) - mean3 = ztf.constant(-0.213) - sigma1 = ztf.constant(0.014) - sigma2 = ztf.constant(0.128) - sigma3 = ztf.constant(0.548) - x1 = (val1-mean1)/sigma1 - x2 = (val2-mean2)/sigma2 - x3 = (val3-mean3)/sigma3 - rho12 = m[0][1] - rho13 = m[0][2] - rho23 = m[1][2] - 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)) - d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) - - fcn = -w/d - chisq = -2*fcn - return chisq - -constraint4 = triGauss(bplus_0, bplus_1, bplus_2) - -# mean1 = ztf.constant(0.466) -# mean2 = ztf.constant(-0.885) -# mean3 = ztf.constant(-0.213) -# sigma1 = ztf.constant(0.014) -# sigma2 = ztf.constant(0.128) -# sigma3 = ztf.constant(0.548) -# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) -# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) -# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) - -# 5. Constraint - Abs. of sum of light contribs - -sum_list_5 = [] - -sum_list_5.append(rho_s*rho_w/rho_m) -sum_list_5.append(omega_s*omega_w/omega_m) -sum_list_5.append(phi_s*phi_w/phi_m) - - -sum_ru_5 = ztf.constant(0.0) - -for part in sum_list_5: - sum_ru_5 += part - -constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) - -# 6. Constraint on phases of Jpsi and Psi2s for cut out fit - - -# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), -# sigma = ztf.constant(jpsi_phase)) -# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), -# sigma = ztf.constant(psi2s_phase)) - -constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) -constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) - -# 7. Constraint on Ctt with higher limits - -constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) - -constraint7dtype = tf.float64 - -# zfit.run(constraint6_0) - -# ztf.convert_to_tensor(constraint6_0) - -#List of all constraints - -constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, - constraint6_0, constraint6_1]#, constraint7] - - -# ## Reset params - -# In[38]: - - -def reset_param_values(): - jpsi_m.set_value(jpsi_mass) - jpsi_s.set_value(jpsi_scale) - jpsi_p.set_value(jpsi_phase) - jpsi_w.set_value(jpsi_width) - psi2s_m.set_value(psi2s_mass) - psi2s_s.set_value(psi2s_scale) - psi2s_p.set_value(psi2s_phase) - psi2s_w.set_value(psi2s_width) - p3770_m.set_value(p3770_mass) - p3770_s.set_value(p3770_scale) - p3770_p.set_value(p3770_phase) - p3770_w.set_value(p3770_width) - p4040_m.set_value(p4040_mass) - p4040_s.set_value(p4040_scale) - p4040_p.set_value(p4040_phase) - p4040_w.set_value(p4040_width) - p4160_m.set_value(p4160_mass) - p4160_s.set_value(p4160_scale) - p4160_p.set_value(p4160_phase) - p4160_w.set_value(p4160_width) - p4415_m.set_value(p4415_mass) - p4415_s.set_value(p4415_scale) - p4415_p.set_value(p4415_phase) - p4415_w.set_value(p4415_width) - rho_m.set_value(rho_mass) - rho_s.set_value(rho_scale) - rho_p.set_value(rho_phase) - rho_w.set_value(rho_width) - omega_m.set_value(omega_mass) - omega_s.set_value(omega_scale) - omega_p.set_value(omega_phase) - omega_w.set_value(omega_width) - phi_m.set_value(phi_mass) - phi_s.set_value(phi_scale) - phi_p.set_value(phi_phase) - phi_w.set_value(phi_width) - Dstar_m.set_value(Dstar_mass) - DDstar_s.set_value(0.0) - DDstar_p.set_value(0.0) - D_m.set_value(D_mass) - Dbar_m.set_value(Dbar_mass) - Dbar_s.set_value(0.0) - Dbar_p.set_value(0.0) - tau_m.set_value(pdg['tau_M']) - Ctt.set_value(0.0) - b0_0.set_value(0.292) - b0_1.set_value(0.281) - b0_2.set_value(0.150) - bplus_0.set_value(0.466) - bplus_1.set_value(-0.885) - bplus_2.set_value(-0.213) - bT_0.set_value(0.460) - bT_1.set_value(-1.089) - bT_2.set_value(-1.114) - - -# # Analysis - -# In[39]: - - -# # zfit.run.numeric_checks = False - -# fitting_range = 'cut' -# 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 -# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR - -# Ctt_list = [] -# Ctt_error_list = [] - -# nr_of_toys = 1 -# if fitting_range == 'cut': -# nevents = int(pdg["number_of_decays"]*cut_BR) -# else: -# nevents = int(pdg["number_of_decays"]) -# # nevents = pdg["number_of_decays"] -# event_stack = 1000000 -# # nevents *= 41 -# # zfit.settings.set_verbosity(10) -# calls = int(nevents/event_stack + 1) - -# total_samp = [] - -# start = time.time() - -# sampler = total_f.create_sampler(n=event_stack) - -# for toy in range(nr_of_toys): - -# ### Generate data - -# # clear_output(wait=True) - -# print("Toy {}: Generating data...".format(toy)) - -# dirName = 'data/zfit_toys/toy_{0}'.format(toy) - -# if not os.path.exists(dirName): -# os.mkdir(dirName) -# print("Directory " , dirName , " Created ") - -# reset_param_values() - -# if fitting_range == 'cut': - -# sampler.resample(n=nevents) -# s = sampler.unstack_x() -# sam = zfit.run(s) -# calls = 0 -# c = 1 - -# else: -# for call in range(calls): - -# sampler.resample(n=event_stack) -# s = sampler.unstack_x() -# sam = zfit.run(s) - -# c = call + 1 - -# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: -# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) - -# print("Toy {}: Data generation finished".format(toy)) - -# ### Load data - -# print("Toy {}: Loading data...".format(toy)) - -# if fitting_range == 'cut': - -# total_samp = sam - -# else: - -# for call in range(calls): -# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: -# sam = pkl.load(input_file) -# total_samp = np.append(total_samp, sam) - -# total_samp = total_samp.astype('float64') - -# if fitting_range == 'full': - -# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) - -# print("Toy {}: Loading data finished".format(toy)) - -# ### Fit data - -# print("Toy {}: Fitting pdf...".format(toy)) - -# for param in total_f.get_dependents(): -# param.randomize() - -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# print("Toy {}: Fitting finished".format(toy)) - -# print("Function minimum:", result.fmin) -# print("Hesse errors:", result.hesse()) - -# params = result.params -# Ctt_list.append(params[Ctt]['value']) -# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) - -# #plotting the result - -# plotdirName = 'data/plots'.format(toy) - -# if not os.path.exists(plotdirName): -# os.mkdir(plotdirName) -# # print("Directory " , dirName , " Created ") - -# probs = total_f.pdf(test_q, norm_range=False) -# calcs_test = zfit.run(probs) -# plt.clf() -# plt.plot(test_q, calcs_test, label = 'pdf') -# plt.legend() -# plt.ylim(0.0, 6e-6) -# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) - -# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) - -# if fitting_range == 'cut': - -# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) - -# tot_sam_1 = total_samp[_1] - -# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) - -# tot_sam_2 = total_samp[_2] - -# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) - -# tot_sam_3 = total_samp[_3] - -# tot_sam = np.append(tot_sam_1, tot_sam_2) -# tot_sam = np.append(tot_sam, tot_sam_3) - -# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) - -# print("Toy {}: Loading data finished".format(toy)) - -# ### Fit data - -# print("Toy {}: Fitting pdf...".format(toy)) - -# for param in total_f_fit.get_dependents(): -# param.randomize() - -# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# print("Function minimum:", result.fmin) -# print("Hesse errors:", result.hesse()) - -# params = result.params - -# if result.converged: -# Ctt_list.append(params[Ctt]['value']) -# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) - -# #plotting the result - -# plotdirName = 'data/plots'.format(toy) - -# if not os.path.exists(plotdirName): -# os.mkdir(plotdirName) -# # print("Directory " , dirName , " Created ") - -# plt.clf() -# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') -# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) - - -# probs = total_f_fit.pdf(test_q, norm_range=False) -# calcs_test = zfit.run(probs) -# plt.clf() -# plt.plot(test_q, calcs_test, label = 'pdf') -# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.legend() -# plt.ylim(0.0, 1.5e-6) -# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) - -# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) - - - -# In[40]: - - -# with open("data/results/Ctt_list.pkl", "wb") as f: -# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) -# with open("data/results/Ctt_error_list.pkl", "wb") as f: -# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) - - -# In[41]: - - -# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) -# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) -# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) -# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) - - -# In[42]: - - -# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) - -# plt.show() - -# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) - -# tot_sam.shape - - -# In[43]: - - -# Ctt.floating = False - - -# In[44]: - - -# zfit.run(nll.value()) - - -# In[45]: - - -# result.fmin - - -# In[46]: - - -# BR_steps = np.linspace(0.0, 1e-3, 11) - - -# # CLS Code - -# In[47]: - - -# zfit.run.numeric_checks = False - -load = False - -bo5 = True - -bo5_set = 5 - -fitting_range = 'cut' -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 -cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR - -Ctt_list = [] -Ctt_error_list = [] - -nr_of_toys = 1 -nevents = int(pdg["number_of_decays"]*cut_BR) -# nevents = pdg["number_of_decays"] -event_stack = 1000000 -# nevents *= 41 -# zfit.settings.set_verbosity(10) - -mi = 0.0 -ma = 1e-3 -ste = 11 - -BR_steps = np.linspace(mi, ma, ste) - -Ctt_steps = np.sqrt(BR_steps/4.2*1000) - -total_samp = [] - -start = time.time() - -Nll_list = [] - -sampler = total_f.create_sampler(n=nevents) - -__ = 0 - - -#----------------------------------------------------- - -if not load: - - for Ctt_step in Ctt_steps: - - __ += 1 - - newset = True - - for floaty in [True, False]: - - Ctt.floating = floaty - - Nll_list.append([]) - - if bo5: - - while len(Nll_list[-1])/bo5_set < nr_of_toys: - - print('Step: {0}/{1}'.format(__, ste)) - - print('Current Ctt: {0}'.format(Ctt_step)) - print('Ctt floating: {0}'.format(floaty)) - - print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) - - reset_param_values() - - if floaty: - Ctt.set_value(Ctt_step) - else: - Ctt.set_value(0.0) - - if newset: - sampler.resample(n=nevents) - s = sampler.unstack_x() - total_samp = zfit.run(s) - calls = 0 - c = 1 - newset = False - - - data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) - - ### Fit data - - for param in total_f_fit.get_dependents(): - param.randomize() - - nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - - minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) - # minimizer._use_tfgrad = False - result = minimizer.minimize(nll) - - # print("Function minimum:", result.fmin) - # print("Hesse errors:", result.hesse()) - - params = result.params - - if result.converged: - Nll_list[-1].append(result.fmin) - - else: - - while len(Nll_list[-1]) < nr_of_toys: - - print('Step: {0}/{1}'.format(__, ste)) - - print('Current Ctt: {0}'.format(Ctt_step)) - print('Ctt floating: {0}'.format(floaty)) - - print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) - - reset_param_values() - - if floaty: - Ctt.set_value(Ctt_step) - else: - Ctt.set_value(0.0) - - if floaty: - sampler.resample(n=nevents) - s = sampler.unstack_x() - total_samp = zfit.run(s) - calls = 0 - c = 1 - - - data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) - - ### Fit data - - for param in total_f_fit.get_dependents(): - param.randomize() - - nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - - minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) - # minimizer._use_tfgrad = False - result = minimizer.minimize(nll) - - # print("Function minimum:", result.fmin) - # print("Hesse errors:", result.hesse()) - - params = result.params - - if result.converged: - Nll_list[-1].append(result.fmin) - - _t = int(time.time()-start) - - print('Time Taken: {}'.format(display_time(int(_t)))) - - print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) - - -# In[48]: - - -if load: - Nll_list = [] - CLs_values = [] - - _dir = 'data/CLs/finished/f1d1' - - jobs = os.listdir(_dir) - - for s in range(ste): - CLs_values.append([]) - - for s in range(2*ste): - Nll_list.append([]) - - for job in jobs: - if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): - print(job) - continue - - with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: - _Nll_list = pkl.load(input_file) - - if bo5: - for s in range(2*ste): - Nll_list[s].append(np.min(_Nll_list[s])) - else: - for s in range(2*ste): - Nll_list[s].extend(_Nll_list[s]) - - with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: - _CLs_values = pkl.load(input_file) - - for s in range(ste): - CLs_values[s].extend(_CLs_values[s]) - - print(np.shape(Nll_list)) - - -# In[50]: - - -dirName = 'data/CLs' - -# if bo5 and not load: -# for s in range(2*ste): -# Nll_list[s] = [np.min(Nll_list[s])] - -if bo5: - CLs_values= [] - for i in range(int(len(Nll_list)/2)): - CLs_values.append([]) - for j in range(len(Nll_list[0])): - CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) - - -if not load: - - CLs_values = [] - - for i in range(int(len(Nll_list)/2)): - CLs_values.append([]) - for j in range(nr_of_toys): - CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) - - if not os.path.exists(dirName): - os.mkdir(dirName) - print("Directory " , dirName , " Created ") - - with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: - pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) - - with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: - pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) - - -# In[51]: - - -# print(CLs_values) -print(Nll_list) - - -# ## Plot - -# In[52]: - - -l = [] - -for i in range(len(CLs_values)): - plt.clf() - plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) - plt.hist(CLs_values[0], bins = 100, label = 'Ctt fixed to 0') - plt.hist(CLs_values[i], bins = 100, label = 'Ctt floating') - plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=0.7, linestyle = 'dotted') - plt.legend() - plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) - - l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) - - -# In[53]: - - -for s in range(len(l)): - print('BR: {}'.format(BR_steps[s])) - print(2*l[s]/len(CLs_values[0])) - print() - - -# In[54]: - - -# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) - - -# In[ ]: - - - - diff --git a/data/CLs/finished/f1d1/2254881/test.png b/data/CLs/finished/f1d1/2254881/test.png deleted file mode 100644 index 1455457..0000000 --- a/data/CLs/finished/f1d1/2254881/test.png +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254886/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/2254886/__pycache__/helperfunctions.cpython-37.pyc deleted file mode 100644 index 00db4a8..0000000 --- a/data/CLs/finished/f1d1/2254886/__pycache__/helperfunctions.cpython-37.pyc +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254886/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/2254886/__pycache__/pdg_const.cpython-37.pyc deleted file mode 100644 index d09bea0..0000000 --- a/data/CLs/finished/f1d1/2254886/__pycache__/pdg_const.cpython-37.pyc +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254886/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/2254886/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl deleted file mode 100644 index 3a2bb99..0000000 --- a/data/CLs/finished/f1d1/2254886/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254886/data/CLs/0.0-0.001_11s--CLs_list.pkl b/data/CLs/finished/f1d1/2254886/data/CLs/0.0-0.001_11s--CLs_list.pkl deleted file mode 100644 index 1414d37..0000000 --- a/data/CLs/finished/f1d1/2254886/data/CLs/0.0-0.001_11s--CLs_list.pkl +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254886/helperfunctions.py b/data/CLs/finished/f1d1/2254886/helperfunctions.py deleted file mode 100644 index 88e120f..0000000 --- a/data/CLs/finished/f1d1/2254886/helperfunctions.py +++ /dev/null @@ -1,33 +0,0 @@ -# some helperfunctions - -import matplotlib -matplotlib.use("agg") -import matplotlib.pyplot as plt - -#Dislpay time (e.g. while generating points) - -display_intervals = ( - ('w', 604800), # 60 * 60 * 24 * 7 - ('d', 86400), # 60 * 60 * 24 - ('h', 3600), # 60 * 60 - ('min', 60), - ('s', 1), - ) - -def display_time(seconds, granularity=2): - result = [] - - for name, count in display_intervals: - value = seconds // count - if value: - seconds -= value * count - if value == 1: - name = name.rstrip('s') - result.append("{} {}".format(value, name)) - return ', '.join(result[:granularity]) - -def prepare_plot(title): - plt.title(title) - plt.grid() - plt.legend(loc = 'best') - plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/2254886/pdg_const.py b/data/CLs/finished/f1d1/2254886/pdg_const.py deleted file mode 100644 index 6645dd7..0000000 --- a/data/CLs/finished/f1d1/2254886/pdg_const.py +++ /dev/null @@ -1,226 +0,0 @@ -pdg = { - - - ###Particle masses### - - "mbstar" : 5415.4, - "mbstar0" : 5711.0, - "B0_M" : 5279.5, - "Bs_M" : 5366.7, - "Bplus_M" : 5279.3, - "Lb_M" : 5619.4, - "D0_M" : 1864.8, - "Dst_M" : 2010, - "pi_M" : 139.6, - "Jpsi_M" : 3096.9, - "Psi2s_M" : 3685.6, - "kaon_M" : 493.7, - "Ks_M" : 497.6, - "phi_M" : 1019.5, - "rho_M" : 775.26, - "rho_width" : 149.1, - "omega_M" : 782.65, - "omega_width" : 8.49, - - "muon_M" : 105.7, - "tau_M": 1776.86, - - "squark_M" : 95.0, - "bquark_M" : 4180.0, - "cquark_M" : 1275.0, - - "Bplus_tau" : 1.638e-12, - - ###Wilson coefficients### - - "C1" : -0.257, - "C2" : 1.009, - "C3" : -0.005, - "C4" : -0.078, - - "C7eff" : -0.306, - "C9eff" : 4.211, - "C10eff" : -4.103, - -# "C7eff": 0.0, -# "C9eff": 0.0, -# "C10eff": 0.0, - - ###Other constants - - "GF" : 1.1663787e-5, - "alpha_ew" : 1.0/137.0, - "Vts" : 0.0394, - "Vtb" : 1.019, - "number_of_decays": 5404696, - - #Formfactor z coefficients - - #"b0" : [0.285, 0.19, -0.17], - #"bplus" : [0.437, -1.41, -2.5], - #"bT" : [0.440, -1.47, -2.7] - - "b0" : [0.292, 0.281, 0.150], - "bplus" : [0.466, -0.885, -0.213], - "bT" : [0.460, -1.089, -1.114], - - "NR_BR": 4.37e-7, - "NR_auc": 0.00133, - - #Resonances format(mass, width, phase, scale) - - # pre scaling - -# "rho": (775.26, 149.0, -0.35, 1.0), - -# "omega": (782.7, 8.5, 0.26, 1.0), - -# "phi": (1019.46, 4.25, 0.5, 1.0), - -# "jpsi": (3096.0, 0.09, -1.5, 2e-2), -# "jpsi_auc": 0.2126825758464027, - -# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), -# "psi2s_auc": 2.802257483178487e-10, - -# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), - -# "p4040": (4039.0, 80.0, -2.52, 2.0), - -# "p4160": (4191.0, 70.0, -1.9, 2.2), - -# "p4415": (4421.0, 62.0, -2.52, 1.0), - - - # after scaling (Phase combination --) - - -# "rho": (743.2, 149.0, -0.22, 1.05), - -# "omega": (782.7, 8.5, 0.38, 6.8), - -# "phi": (1013.5, 4.25, 0.62, 19.2), - -# "jpsi": (3096.1, 0.09, 1.63, 9897.0), -# "jpsi_auc": 0.2126825758464027, -# "jpsi_phase_unc": 0.05, - -# "psi2s": (3686.0, 0.3, 1.8, 1396.0), -# "psi2s_auc": 0.0151332263, -# "psi2s_phase_unc": 0.1, - -# "p3770": (3773.0, 27.2, -2.95, 2.5), - -# "p4040": (4039.0, 80.0, -2.75, 1.01), - -# "p4160": (4191.0, 70.0, -2.28, 2.2), - -# "p4415": (4421.0, 62.0, -2.31, 1.24), - - # Phase combination of paper ++ - -# "rho": (743.2, 149.0, -0.35, 1.05), - -# "omega": (782.7, 8.5, 0.26, 6.8), - -# "phi": (1013.5, 4.25, 0.47, 19.2), - -# "jpsi": (3096.1, 0.09, -1.66, 9897.0), -# "jpsi_auc": 0.2126825758464027, -# "jpsi_phase_unc": 0.05, - -# "psi2s": (3686.0, 0.3, -1.93, 1396.0), -# "psi2s_auc": 0.0151332263, -# "psi2s_phase_unc": 0.1, - -# "p3770": (3773.0, 27.2, -2.13, 2.5), - -# "p4040": (4039.0, 80.0, -2.52, 1.01), - -# "p4160": (4191.0, 70.0, -1.90, 2.2), - -# "p4415": (4421.0, 62.0, -2.52, 1.24), - - # Phase combination of paper +- - - # "rho": (743.2, 149.0, -0.26, 1.05), - # - # "omega": (782.7, 8.5, 0.35, 6.8), - # - # "phi": (1013.5, 4.25, 0.58, 19.2), - # - # "jpsi": (3096.1, 0.09, 1.47, 9897.0), - # "jpsi_auc": 0.2126825758464027, - # "jpsi_phase_unc": 0.05, - # - # "psi2s": (3686.0, 0.3, -2.21, 1396.0), - # "psi2s_auc": 0.0151332263, - # "psi2s_phase_unc": 0.1, - # - # "p3770": (3773.0, 27.2, -2.140, 2.5), - # - # "p4040": (4039.0, 80.0, -2.64, 1.01), - # - # "p4160": (4191.0, 70.0, -2.11, 2.2), - # - # "p4415": (4421.0, 62.0, -2.42, 1.24), - - # Phase combination of paper -+ - - "rho": (743.2, 149.0, -0.30, 1.05), - - "omega": (782.7, 8.5, 0.30, 6.8), - - "phi": (1013.5, 4.25, 0.51, 19.2), - - "jpsi": (3096.1, 0.09, -1.5, 9897.0), - "jpsi_auc": 0.2126825758464027, - "jpsi_phase_unc": 0.05, - - "psi2s": (3686.0, 0.3, 2.08, 1396.0), - "psi2s_auc": 0.0151332263, - "psi2s_phase_unc": 0.1, - - "p3770": (3773.0, 27.2, -2.89, 2.5), - - "p4040": (4039.0, 80.0, -2.69, 1.01), - - "p4160": (4191.0, 70.0, -2.13, 2.2), - - "p4415": (4421.0, 62.0, -2.43, 1.24), - - - # zeroing resonances - -# "rho": (775.26, 149.0, -0.35, 0.0), -# "omega": (782.7, 8.5, 0.26, 0.0), -# "phi": (1019.46, 4.25, 0.5, 0.0), -# "jpsi": (3096.0, 0.09, -1.5, 0.0), -# "psi2s": (3686.0, 0.3, -1.5, 0.0), -# "p3770": (3773.0, 27.2, -2.13, 0.0), -# "p4040": (4039.0, 80.0, -2.52, 0.0), -# "p4160": (4147.0, 22.0, -1.9, 0.0), -# "p4415": (4421.0, 62.0, -2.52, 0.0), - - # 2P contributions format(mass, amp, phase) - -# "D_bar": ( - - #general - - "rho_BR": 1.7e-10, - "omega_BR": 4.9e-10, - "phi_BR": 2.5e-9, - "jpsi_BR": 6.02e-5, - "psi2s_BR": 4.97e-6, - "p3770_BR": 1.38e-9, - "p4040_BR": 4.2e-10, - "p4160_BR": 2.6e-9, - "p4415_BR": 6.1e-10, - -# Estimates - "Dbar_scale": 1.46, #with phase = pi - - "DDstar_scale": 2.41, #with phase = pi - - } diff --git a/data/CLs/finished/f1d1/2254886/raremodel-nb1.py b/data/CLs/finished/f1d1/2254886/raremodel-nb1.py deleted file mode 100644 index 1a5d9be..0000000 --- a/data/CLs/finished/f1d1/2254886/raremodel-nb1.py +++ /dev/null @@ -1,1939 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -# # Import - -# In[1]: - - -import os - -# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" - -import numpy as np -from pdg_const import pdg -import matplotlib -import matplotlib.pyplot as plt -import pickle as pkl -import sys -import time -from helperfunctions import display_time, prepare_plot -import cmath as c -import scipy.integrate as integrate -from scipy.optimize import fminbound -from array import array as arr -import collections -from itertools import compress -import tensorflow as tf -import zfit -from zfit import ztf -# from IPython.display import clear_output -import os -import tensorflow_probability as tfp -tfd = tfp.distributions - - -# In[2]: - - -# chunksize = 10000 -# zfit.run.chunking.active = True -# zfit.run.chunking.max_n_points = chunksize - - -# # Build model and graphs -# ## Create graphs - -# In[ ]: - - - - - -# In[3]: - - -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 - #check if subscript is viable - - if subscript != "0" and subscript != "+" and subscript != "T": - raise ValueError('Wrong subscript entered, choose either 0, + or T') - - #get constants - - mK = ztf.constant(pdg['Ks_M']) - mbstar0 = ztf.constant(pdg["mbstar0"]) - mbstar = ztf.constant(pdg["mbstar"]) - - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mB = ztf.constant(pdg['Bplus_M']) - - #N comes from derivation in paper - - N = 3 - - #some helperfunctions - - tpos = (mB - mK)**2 - tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 - - z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) - z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) - z = tf.divide(z_oben, z_unten) - - #calculate f0 - - if subscript == "0": - prefactor = 1/(1 - q2/(mbstar0**2)) - _sum = 0 - b0 = [b0_0, b0_1, b0_2] - - for i in range(N): - _sum += b0[i]*(tf.pow(z,i)) - - return ztf.to_complex(prefactor * _sum) - - #calculate f+ or fT - - else: - prefactor = 1/(1 - q2/(mbstar**2)) - _sum = 0 - - if subscript == "T": - bT = [bT_0, bT_1, bT_2] - for i in range(N): - _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) - else: - bplus = [bplus_0, bplus_1, bplus_2] - for i in range(N): - _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) - - return ztf.to_complex(prefactor * _sum) - -def resonance(q, _mass, width, phase, scale): - - q2 = tf.pow(q, 2) - - mmu = ztf.constant(pdg['muon_M']) - - p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) - - p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) - - gamma_j = tf.divide(p, q) * _mass * width / p0 - - #Calculate the resonance - - _top = tf.complex(_mass * width, ztf.constant(0.0)) - - _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) - - com = _top/_bottom - - #Rotate by the phase - - r = ztf.to_complex(scale*tf.abs(com)) - - _phase = tf.angle(com) - - _phase += phase - - com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) - - return com - - -def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): - - GF = ztf.constant(pdg['GF']) - alpha_ew = ztf.constant(pdg['alpha_ew']) - Vtb = ztf.constant(pdg['Vtb']) - Vts = ztf.constant(pdg['Vts']) - C10eff = ztf.constant(pdg['C10eff']) - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mK = ztf.constant(pdg['Ks_M']) - mB = ztf.constant(pdg['Bplus_M']) - - q2 = tf.pow(q, 2) - - #Some helperfunctions - - beta = 1. - 4. * mmu**2. / q2 - - 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.) - - #prefactor in front of whole bracket - - prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) - - #left term in bracket - - 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) - - #middle term in bracket - - _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) - - _under = q2 * mB**2. - - 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) - - #Note sqrt(q2) comes from derivation as we use q2 and plot q - - return prefactor1 * (bracket_left + bracket_middle) * 2 * q - -def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): - - q2 = tf.pow(q, 2) - - GF = ztf.constant(pdg['GF']) - alpha_ew = ztf.constant(pdg['alpha_ew']) - Vtb = ztf.constant(pdg['Vtb']) - Vts = ztf.constant(pdg['Vts']) - C7eff = ztf.constant(pdg['C7eff']) - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mK = ztf.constant(pdg['Ks_M']) - mB = ztf.constant(pdg['Bplus_M']) - - #Some helperfunctions - - beta = 1. - 4. * mmu**2. / q2 - - 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) - - #prefactor in front of whole bracket - - prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) - - #right term in bracket - - prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) - - 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) - - bracket_right = prefactor2 * abs_bracket - - #Note sqrt(q2) comes from derivation as we use q2 and plot q - - return prefactor1 * bracket_right * 2 * q - -def c9eff(q, funcs): - - C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) - - c9 = C9eff_nr + funcs - - return c9 - - -# In[4]: - - -def G(y): - - def inner_rect_bracket(q): - return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) - - def inner_right(q): - return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) - - big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) - - return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket - -def h_S(m, q): - - 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))) - -def h_P(m, q): - - 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) - -def two_p_ccbar(mD, m_D_bar, m_D_star, q): - - - #Load constants - nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) - nu_D = ztf.to_complex(pdg["nu_D"]) - nu_D_star = ztf.to_complex(pdg["nu_D_star"]) - - phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) - phase_D = ztf.to_complex(pdg["phase_D"]) - phase_D_star = ztf.to_complex(pdg["phase_D_star"]) - - #Calculation - left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) - - right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) - - right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) - - return left_part + right_part_D + right_part_D_star - - -# ## Build pdf - -# In[5]: - - -class total_pdf_cut(zfit.pdf.ZPDF): - _N_OBS = 1 # dimension, can be omitted - _PARAMS = ['b0_0', 'b0_1', 'b0_2', - 'bplus_0', 'bplus_1', 'bplus_2', - 'bT_0', 'bT_1', 'bT_2', - 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', - 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', - 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', - 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', - 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', - 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', - 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', - 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', - 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', - 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', - 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', - 'tau_mass', 'C_tt'] -# the name of the parameters - - def _unnormalized_pdf(self, x): - - x = x.unstack_x() - - b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] - bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] - bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] - - def rho_res(q): - return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], - phase = self.params['rho_phase'], width = self.params['rho_width']) - - def omega_res(q): - return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], - phase = self.params['omega_phase'], width = self.params['omega_width']) - - def phi_res(q): - return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], - phase = self.params['phi_phase'], width = self.params['phi_width']) - - def jpsi_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], - scale = self.params['jpsi_scale'], - phase = self.params['jpsi_phase'], - width = self.params['jpsi_width']) - def psi2s_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], - scale = self.params['psi2s_scale'], - phase = self.params['psi2s_phase'], - width = self.params['psi2s_width']) - def p3770_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], - scale = self.params['p3770_scale'], - phase = self.params['p3770_phase'], - width = self.params['p3770_width']) - - def p4040_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], - scale = self.params['p4040_scale'], - phase = self.params['p4040_phase'], - width = self.params['p4040_width']) - - def p4160_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], - scale = self.params['p4160_scale'], - phase = self.params['p4160_phase'], - width = self.params['p4160_width']) - - def p4415_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], - scale = self.params['p4415_scale'], - phase = self.params['p4415_phase'], - width = self.params['p4415_width']) - - def P2_D(q): - 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)) - 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))) - return Dbar_contrib + DDstar_contrib - - def ttau_cusp(q): - 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))) - - - 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) - - vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - tot = vec_f + axiv_nr - - #Cut out jpsi and psi2s - - tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) - - tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) - - return tot - -class total_pdf_full(zfit.pdf.ZPDF): - _N_OBS = 1 # dimension, can be omitted - _PARAMS = ['b0_0', 'b0_1', 'b0_2', - 'bplus_0', 'bplus_1', 'bplus_2', - 'bT_0', 'bT_1', 'bT_2', - 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', - 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', - 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', - 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', - 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', - 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', - 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', - 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', - 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', - 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', - 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', - 'tau_mass', 'C_tt'] -# the name of the parameters - - def _unnormalized_pdf(self, x): - - x = x.unstack_x() - - b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] - bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] - bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] - - def rho_res(q): - return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], - phase = self.params['rho_phase'], width = self.params['rho_width']) - - def omega_res(q): - return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], - phase = self.params['omega_phase'], width = self.params['omega_width']) - - def phi_res(q): - return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], - phase = self.params['phi_phase'], width = self.params['phi_width']) - - def jpsi_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], - scale = self.params['jpsi_scale'], - phase = self.params['jpsi_phase'], - width = self.params['jpsi_width']) - def psi2s_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], - scale = self.params['psi2s_scale'], - phase = self.params['psi2s_phase'], - width = self.params['psi2s_width']) - def p3770_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], - scale = self.params['p3770_scale'], - phase = self.params['p3770_phase'], - width = self.params['p3770_width']) - - def p4040_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], - scale = self.params['p4040_scale'], - phase = self.params['p4040_phase'], - width = self.params['p4040_width']) - - def p4160_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], - scale = self.params['p4160_scale'], - phase = self.params['p4160_phase'], - width = self.params['p4160_width']) - - def p4415_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], - scale = self.params['p4415_scale'], - phase = self.params['p4415_phase'], - width = self.params['p4415_width']) - - def P2_D(q): - 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)) - 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))) - return Dbar_contrib + DDstar_contrib - - def ttau_cusp(q): - 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))) - - - 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) - - vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - tot = vec_f + axiv_nr - - #Cut out jpsi and psi2s - -# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) - -# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) - - return tot - - -# ## Setup parameters - -# In[6]: - - -# formfactors - -b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) - -bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) -bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) -bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) - -bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) - - -#rho - -rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] - -rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) -rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) -rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#omega - -omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] - -omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) -omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) -omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - - -#phi - -phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] - -phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) -phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) -phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#jpsi - -jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] - -jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) -jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) -jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi2s - -psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] - -psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) -psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) -psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(3770) - -p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] - -p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) -p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) -p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4040) - -p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] - -p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) -p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) -p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4160) - -p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] - -p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) -p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) -p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4415) - -p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] - -p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) -p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) -p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - - -# ## Dynamic generation of 2 particle contribution - -# In[7]: - - -m_c = 1300 - -Dbar_phase = 0.0 -DDstar_phase = 0.0 -Dstar_mass = pdg['Dst_M'] -Dbar_mass = pdg['D0_M'] -D_mass = pdg['D0_M'] - -Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) -Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) -Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) -DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) -Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) -D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) -DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) - - -# ## Tau parameters - -# In[8]: - - -tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) -Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) - - -# ## Load data - -# In[9]: - - -x_min = 2*pdg['muon_M'] -x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) - -# # Full spectrum - -obs_toy = zfit.Space('q', limits = (x_min, x_max)) - -# Jpsi and Psi2s cut out - -obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) -obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) -obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) - -obs_fit = obs1 + obs2 + obs3 - -# 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: -# part_set = pkl.load(input_file) - -# x_part = part_set['x_part'] - -# x_part = x_part.astype('float64') - -# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) - - -# ## Setup pdf - -# In[10]: - - -total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, - psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, - p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, - p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, - p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, - p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, - rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, - omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, - phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, - Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, - Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, - tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, - bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, - bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) - -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, - psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, - p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, - p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, - p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, - p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, - rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, - omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, - phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, - Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, - Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, - tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, - bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, - bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) - -# print(total_pdf.obs) - -# print(calcs_test) - -# for param in total_f.get_dependents(): -# print(zfit.run(param)) - - -# In[11]: - - -total_f_fit.normalization(obs_toy) - - -# ## Test if graphs actually work and compute values - -# In[12]: - - -# def total_test_tf(xq): - -# def jpsi_res(q): -# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) - -# def psi2s_res(q): -# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) - -# def cusp(q): -# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) - -# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) - -# vec_f = vec(xq, funcs) - -# axiv_nr = axiv_nonres(xq) - -# tot = vec_f + axiv_nr - -# return tot - -# def jpsi_res(q): -# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) - -# calcs = zfit.run(total_test_tf(x_part)) - -test_q = np.linspace(x_min, x_max, int(2e6)) - -probs = total_f_fit.pdf(test_q, norm_range=False) - -calcs_test = zfit.run(probs) -# res_y = zfit.run(jpsi_res(test_q)) -# b0 = [b0_0, b0_1, b0_2] -# bplus = [bplus_0, bplus_1, bplus_2] -# bT = [bT_0, bT_1, bT_2] -# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) -# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) -# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) - - -# In[13]: - - -plt.clf() -# plt.plot(x_part, calcs, '.') -plt.plot(test_q, calcs_test, label = 'pdf') -# plt.plot(test_q, f0_y, label = '0') -# plt.plot(test_q, fT_y, label = 'T') -# plt.plot(test_q, fplus_y, label = '+') -# plt.plot(test_q, res_y, label = 'res') -plt.legend() -plt.ylim(0.0, 1.5e-6) -# plt.yscale('log') -# plt.xlim(770, 785) -plt.savefig('test.png') -# print(jpsi_width) - - -# In[14]: - - - - -# probs = mixture.prob(test_q) -# probs_np = zfit.run(probs) -# probs_np *= np.max(calcs_test) / np.max(probs_np) -# plt.figure() -# plt.semilogy(test_q, probs_np,label="importance sampling") -# plt.semilogy(test_q, calcs_test, label = 'pdf') - - -# In[15]: - - -# 0.213/(0.00133+0.213+0.015) - - -# ## Adjust scaling of different parts - -# In[16]: - - -total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) -# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) -# inte_fl = zfit.run(inte) -# print(inte_fl/4500) -# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) - - -# In[17]: - - -# # print("jpsi:", inte_fl) -# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - -# # print("psi2s:", inte_fl) -# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - -# name = "phi" - -# print(name+":", inte_fl) -# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - - -# print(x_min) -# print(x_max) -# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) -# total_f.update_integration_options(mc_sampler=lambda dim, num_results, -# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), -# draws_per_dim=1000000) -# # _ = [] - -# # for i in range(10): - -# # inte = total_f.integrate(limits = (x_min, x_max)) -# # inte_fl = zfit.run(inte) -# # print(inte_fl) -# # _.append(inte_fl) - -# # print("mean:", np.mean(_)) - -# _ = time.time() - -# inte = total_f.integrate(limits = (x_min, x_max)) -# inte_fl = zfit.run(inte) -# print(inte_fl) -# print("Time taken: {}".format(display_time(int(time.time() - _)))) - -# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) -# print(0.25**2*4.2/1000) - - -# # Sampling -# ## Mixture distribution for sampling - -# In[18]: - - - - -# print(list_of_borders[:9]) -# print(list_of_borders[-9:]) - - -class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): - def __call__(self, limits, dtype, n_to_produce): - # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) - low, high = limits.limit1d - low = tf.cast(low, dtype=dtype) - high = tf.cast(high, dtype=dtype) -# uniform = tfd.Uniform(low=low, high=high) -# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) -# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) - -# list_of_borders = [] -# _p = [] -# splits = 10 - -# _ = np.linspace(x_min, x_max, splits) - -# for i in range(splits): -# list_of_borders.append(tf.constant(_[i], dtype=dtype)) -# _p.append(tf.constant(1/splits, dtype=dtype)) - -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), -# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], -# high=list_of_borders[-(splits-1):])) - mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), - tf.constant(0.93, dtype=dtype), - tf.constant(0.05, dtype=dtype), - tf.constant(0.065, dtype=dtype), - tf.constant(0.04, dtype=dtype), - tf.constant(0.05, dtype=dtype)]), - components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), - tf.constant(3090, dtype=dtype), - tf.constant(3681, dtype=dtype), - tf.constant(3070, dtype=dtype), - tf.constant(1000, dtype=dtype), - tf.constant(3660, dtype=dtype)], - high=[tf.constant(x_max, dtype=dtype), - tf.constant(3102, dtype=dtype), - tf.constant(3691, dtype=dtype), - tf.constant(3110, dtype=dtype), - tf.constant(1040, dtype=dtype), - tf.constant(3710, dtype=dtype)])) -# dtype = tf.float64 -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), -# tf.constant(0.90, dtype=dtype), -# tf.constant(0.02, dtype=dtype), -# tf.constant(0.07, dtype=dtype), -# tf.constant(0.02, dtype=dtype)]), -# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), -# tf.constant(3089, dtype=dtype), -# tf.constant(3103, dtype=dtype), -# tf.constant(3681, dtype=dtype), -# tf.constant(3691, dtype=dtype)], -# high=[tf.constant(3089, dtype=dtype), -# tf.constant(3103, dtype=dtype), -# tf.constant(3681, dtype=dtype), -# tf.constant(3691, dtype=dtype), -# tf.constant(x_max, dtype=dtype)])) -# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) -# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) - sample = mixture.sample((n_to_produce, 1)) -# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) - weights = mixture.prob(sample)[:,0] -# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) - # sample = tf.expand_dims(sample, axis=-1) -# print(sample, weights) - -# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) - weights_max = None - thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) - return sample, thresholds, weights, weights_max, n_to_produce - - -# In[19]: - - -# total_f._sample_and_weights = UniformSampleAndWeights - - -# In[20]: - - -# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) - - -# In[21]: - - -# zfit.settings.set_verbosity(10) - - -# In[22]: - - -# # zfit.run.numeric_checks = False - -# nr_of_toys = 1 -# nevents = int(pdg["number_of_decays"]) -# nevents = pdg["number_of_decays"] -# event_stack = 1000000 -# # zfit.settings.set_verbosity(10) -# calls = int(nevents/event_stack + 1) - -# total_samp = [] - -# start = time.time() - -# sampler = total_f.create_sampler(n=event_stack) - -# for toy in range(nr_of_toys): - -# dirName = 'data/zfit_toys/toy_{0}'.format(toy) - -# if not os.path.exists(dirName): -# os.mkdir(dirName) -# print("Directory " , dirName , " Created ") - -# for call in range(calls): - -# sampler.resample(n=event_stack) -# s = sampler.unstack_x() -# sam = zfit.run(s) -# # clear_output(wait=True) - -# c = call + 1 - -# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) - -# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: -# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) - - -# In[23]: - - -# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: -# sam = pkl.load(input_file) -# print(sam[:10]) - -# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: -# sam2 = pkl.load(input_file) -# print(sam2[:10]) - -# print(np.sum(sam-sam2)) - - -# In[24]: - - -# print("Time to generate full toy: {} s".format(int(time.time()-start))) - -# total_samp = [] - -# for call in range(calls): -# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: -# sam = pkl.load(input_file) -# total_samp = np.append(total_samp, sam) - -# total_samp = total_samp.astype('float64') - -# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) - -# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) - -# print(total_samp[:nevents].shape) - - -# In[25]: - - -# plt.clf() - -# bins = int((x_max-x_min)/7) - -# # calcs = zfit.run(total_test_tf(samp)) -# print(total_samp[:nevents].shape) - -# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') -# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') - -# # plt.plot(sam, calcs, '.') -# # plt.plot(test_q, calcs_test) -# # plt.yscale('log') -# plt.ylim(0, 200) -# # plt.xlim(3080, 3110) - -# plt.legend() - -# plt.savefig('test2.png') - - -# In[26]: - - -# sampler = total_f.create_sampler(n=nevents) -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) - -# # for param in pdf.get_dependents(): -# # param.set_value(initial_value) - -# sampler.resample(n=nevents) - -# # Randomise initial values -# # for param in pdf.get_dependents(): -# # param.set_value(random value here) - -# # Minimise the NLL -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) -# minimum = minimizer.minimize(nll) - - -# In[27]: - - -# jpsi_width - - -# In[28]: - - -# plt.hist(sample, weights=1 / prob(sample)) - - -# # Fitting - -# In[29]: - - -# start = time.time() - -# for param in total_f.get_dependents(): -# param.randomize() - -# # for param in total_f.get_dependents(): -# # print(zfit.run(param)) - -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# # param_errors = result.error() - -# # for var, errors in param_errors.items(): -# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) - -# print("Function minimum:", result.fmin) -# # print("Results:", result.params) -# print("Hesse errors:", result.hesse()) - - -# In[30]: - - -# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) - -# # probs = total_f.pdf(test_q) - -# calcs_test = zfit.run(probs) -# res_y = zfit.run(jpsi_res(test_q)) - - -# In[31]: - - -# plt.clf() -# # plt.plot(x_part, calcs, '.') -# plt.plot(test_q, calcs_test, label = 'pdf') -# # plt.plot(test_q, res_y, label = 'res') -# plt.legend() -# plt.ylim(0.0, 10e-6) -# # plt.yscale('log') -# # plt.xlim(3080, 3110) -# plt.savefig('test3.png') -# # print(jpsi_width) - - -# In[32]: - - -# _tot = 4.37e-7+6.02e-5+4.97e-6 -# _probs = [] -# _probs.append(6.02e-5/_tot) -# _probs.append(4.97e-6/_tot) -# _probs.append(4.37e-7/_tot) -# print(_probs) - - -# In[33]: - - -# dtype = 'float64' -# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), -# tf.constant(0.917, dtype=dtype), -# tf.constant(0.076, dtype=dtype)]), -# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), -# tf.constant(3080, dtype=dtype), -# tf.constant(3670, dtype=dtype)], -# high=[tf.constant(x_max, dtype=dtype), -# tf.constant(3112, dtype=dtype), -# tf.constant(3702, dtype=dtype)])) -# # for i in range(10): -# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) - - -# In[34]: - - -# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) -# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) - - -# In[35]: - - -# def jpsi_res(q): -# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, -# phase = jpsi_phase, width = jpsi_width) - -# def psi2s_res(q): -# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, -# phase = psi2s_phase, width = psi2s_width) - -# def p3770_res(q): -# return resonance(q, _mass = p3770_mass, scale = p3770_scale, -# phase = p3770_phase, width = p3770_width) - -# def p4040_res(q): -# return resonance(q, _mass = p4040_mass, scale = p4040_scale, -# phase = p4040_phase, width = p4040_width) - -# def p4160_res(q): -# return resonance(q, _mass = p4160_mass, scale = p4160_scale, -# phase = p4160_phase, width = p4160_width) - -# def p4415_res(q): -# return resonance(q, _mass = p4415_mass, scale = p4415_scale, -# phase = p4415_phase, width = p4415_width) - - -# In[36]: - - -# 0.15**2*4.2/1000 -# result.hesse() - - -# ## Constraints - -# In[37]: - - -# 1. Constraint - Real part of sum of Psi contrib and D contribs - -sum_list = [] - -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)))) -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)))) -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)))) -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)))) -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)))) -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)))) -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))))) -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)))) - -sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) - -for part in sum_list: - sum_ru_1 += part - -sum_1 = tf.math.real(sum_ru_1) -# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), -# sigma = ztf.constant(2.2*10**-8)) - -constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) - -# 2. Constraint - Abs. of sum of Psi contribs and D contribs - -sum_2 = tf.abs(sum_ru_1) -constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) - -# 3. Constraint - Maximum eta of D contribs - -constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) - -constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) - -# 4. Constraint - Formfactor multivariant gaussian covariance fplus - -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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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.)]] - -def triGauss(val1,val2,val3,m = Cov_matrix): - - mean1 = ztf.constant(0.466) - mean2 = ztf.constant(-0.885) - mean3 = ztf.constant(-0.213) - sigma1 = ztf.constant(0.014) - sigma2 = ztf.constant(0.128) - sigma3 = ztf.constant(0.548) - x1 = (val1-mean1)/sigma1 - x2 = (val2-mean2)/sigma2 - x3 = (val3-mean3)/sigma3 - rho12 = m[0][1] - rho13 = m[0][2] - rho23 = m[1][2] - 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)) - d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) - - fcn = -w/d - chisq = -2*fcn - return chisq - -constraint4 = triGauss(bplus_0, bplus_1, bplus_2) - -# mean1 = ztf.constant(0.466) -# mean2 = ztf.constant(-0.885) -# mean3 = ztf.constant(-0.213) -# sigma1 = ztf.constant(0.014) -# sigma2 = ztf.constant(0.128) -# sigma3 = ztf.constant(0.548) -# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) -# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) -# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) - -# 5. Constraint - Abs. of sum of light contribs - -sum_list_5 = [] - -sum_list_5.append(rho_s*rho_w/rho_m) -sum_list_5.append(omega_s*omega_w/omega_m) -sum_list_5.append(phi_s*phi_w/phi_m) - - -sum_ru_5 = ztf.constant(0.0) - -for part in sum_list_5: - sum_ru_5 += part - -constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) - -# 6. Constraint on phases of Jpsi and Psi2s for cut out fit - - -# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), -# sigma = ztf.constant(jpsi_phase)) -# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), -# sigma = ztf.constant(psi2s_phase)) - -constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) -constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) - -# 7. Constraint on Ctt with higher limits - -constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) - -constraint7dtype = tf.float64 - -# zfit.run(constraint6_0) - -# ztf.convert_to_tensor(constraint6_0) - -#List of all constraints - -constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, - constraint6_0, constraint6_1]#, constraint7] - - -# ## Reset params - -# In[38]: - - -def reset_param_values(): - jpsi_m.set_value(jpsi_mass) - jpsi_s.set_value(jpsi_scale) - jpsi_p.set_value(jpsi_phase) - jpsi_w.set_value(jpsi_width) - psi2s_m.set_value(psi2s_mass) - psi2s_s.set_value(psi2s_scale) - psi2s_p.set_value(psi2s_phase) - psi2s_w.set_value(psi2s_width) - p3770_m.set_value(p3770_mass) - p3770_s.set_value(p3770_scale) - p3770_p.set_value(p3770_phase) - p3770_w.set_value(p3770_width) - p4040_m.set_value(p4040_mass) - p4040_s.set_value(p4040_scale) - p4040_p.set_value(p4040_phase) - p4040_w.set_value(p4040_width) - p4160_m.set_value(p4160_mass) - p4160_s.set_value(p4160_scale) - p4160_p.set_value(p4160_phase) - p4160_w.set_value(p4160_width) - p4415_m.set_value(p4415_mass) - p4415_s.set_value(p4415_scale) - p4415_p.set_value(p4415_phase) - p4415_w.set_value(p4415_width) - rho_m.set_value(rho_mass) - rho_s.set_value(rho_scale) - rho_p.set_value(rho_phase) - rho_w.set_value(rho_width) - omega_m.set_value(omega_mass) - omega_s.set_value(omega_scale) - omega_p.set_value(omega_phase) - omega_w.set_value(omega_width) - phi_m.set_value(phi_mass) - phi_s.set_value(phi_scale) - phi_p.set_value(phi_phase) - phi_w.set_value(phi_width) - Dstar_m.set_value(Dstar_mass) - DDstar_s.set_value(0.0) - DDstar_p.set_value(0.0) - D_m.set_value(D_mass) - Dbar_m.set_value(Dbar_mass) - Dbar_s.set_value(0.0) - Dbar_p.set_value(0.0) - tau_m.set_value(pdg['tau_M']) - Ctt.set_value(0.0) - b0_0.set_value(0.292) - b0_1.set_value(0.281) - b0_2.set_value(0.150) - bplus_0.set_value(0.466) - bplus_1.set_value(-0.885) - bplus_2.set_value(-0.213) - bT_0.set_value(0.460) - bT_1.set_value(-1.089) - bT_2.set_value(-1.114) - - -# # Analysis - -# In[39]: - - -# # zfit.run.numeric_checks = False - -# fitting_range = 'cut' -# 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 -# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR - -# Ctt_list = [] -# Ctt_error_list = [] - -# nr_of_toys = 1 -# if fitting_range == 'cut': -# nevents = int(pdg["number_of_decays"]*cut_BR) -# else: -# nevents = int(pdg["number_of_decays"]) -# # nevents = pdg["number_of_decays"] -# event_stack = 1000000 -# # nevents *= 41 -# # zfit.settings.set_verbosity(10) -# calls = int(nevents/event_stack + 1) - -# total_samp = [] - -# start = time.time() - -# sampler = total_f.create_sampler(n=event_stack) - -# for toy in range(nr_of_toys): - -# ### Generate data - -# # clear_output(wait=True) - -# print("Toy {}: Generating data...".format(toy)) - -# dirName = 'data/zfit_toys/toy_{0}'.format(toy) - -# if not os.path.exists(dirName): -# os.mkdir(dirName) -# print("Directory " , dirName , " Created ") - -# reset_param_values() - -# if fitting_range == 'cut': - -# sampler.resample(n=nevents) -# s = sampler.unstack_x() -# sam = zfit.run(s) -# calls = 0 -# c = 1 - -# else: -# for call in range(calls): - -# sampler.resample(n=event_stack) -# s = sampler.unstack_x() -# sam = zfit.run(s) - -# c = call + 1 - -# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: -# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) - -# print("Toy {}: Data generation finished".format(toy)) - -# ### Load data - -# print("Toy {}: Loading data...".format(toy)) - -# if fitting_range == 'cut': - -# total_samp = sam - -# else: - -# for call in range(calls): -# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: -# sam = pkl.load(input_file) -# total_samp = np.append(total_samp, sam) - -# total_samp = total_samp.astype('float64') - -# if fitting_range == 'full': - -# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) - -# print("Toy {}: Loading data finished".format(toy)) - -# ### Fit data - -# print("Toy {}: Fitting pdf...".format(toy)) - -# for param in total_f.get_dependents(): -# param.randomize() - -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# print("Toy {}: Fitting finished".format(toy)) - -# print("Function minimum:", result.fmin) -# print("Hesse errors:", result.hesse()) - -# params = result.params -# Ctt_list.append(params[Ctt]['value']) -# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) - -# #plotting the result - -# plotdirName = 'data/plots'.format(toy) - -# if not os.path.exists(plotdirName): -# os.mkdir(plotdirName) -# # print("Directory " , dirName , " Created ") - -# probs = total_f.pdf(test_q, norm_range=False) -# calcs_test = zfit.run(probs) -# plt.clf() -# plt.plot(test_q, calcs_test, label = 'pdf') -# plt.legend() -# plt.ylim(0.0, 6e-6) -# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) - -# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) - -# if fitting_range == 'cut': - -# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) - -# tot_sam_1 = total_samp[_1] - -# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) - -# tot_sam_2 = total_samp[_2] - -# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) - -# tot_sam_3 = total_samp[_3] - -# tot_sam = np.append(tot_sam_1, tot_sam_2) -# tot_sam = np.append(tot_sam, tot_sam_3) - -# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) - -# print("Toy {}: Loading data finished".format(toy)) - -# ### Fit data - -# print("Toy {}: Fitting pdf...".format(toy)) - -# for param in total_f_fit.get_dependents(): -# param.randomize() - -# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# print("Function minimum:", result.fmin) -# print("Hesse errors:", result.hesse()) - -# params = result.params - -# if result.converged: -# Ctt_list.append(params[Ctt]['value']) -# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) - -# #plotting the result - -# plotdirName = 'data/plots'.format(toy) - -# if not os.path.exists(plotdirName): -# os.mkdir(plotdirName) -# # print("Directory " , dirName , " Created ") - -# plt.clf() -# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') -# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) - - -# probs = total_f_fit.pdf(test_q, norm_range=False) -# calcs_test = zfit.run(probs) -# plt.clf() -# plt.plot(test_q, calcs_test, label = 'pdf') -# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.legend() -# plt.ylim(0.0, 1.5e-6) -# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) - -# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) - - - -# In[40]: - - -# with open("data/results/Ctt_list.pkl", "wb") as f: -# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) -# with open("data/results/Ctt_error_list.pkl", "wb") as f: -# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) - - -# In[41]: - - -# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) -# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) -# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) -# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) - - -# In[42]: - - -# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) - -# plt.show() - -# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) - -# tot_sam.shape - - -# In[43]: - - -# Ctt.floating = False - - -# In[44]: - - -# zfit.run(nll.value()) - - -# In[45]: - - -# result.fmin - - -# In[46]: - - -# BR_steps = np.linspace(0.0, 1e-3, 11) - - -# # CLS Code - -# In[47]: - - -# zfit.run.numeric_checks = False - -load = False - -bo5 = True - -bo5_set = 5 - -fitting_range = 'cut' -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 -cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR - -Ctt_list = [] -Ctt_error_list = [] - -nr_of_toys = 1 -nevents = int(pdg["number_of_decays"]*cut_BR) -# nevents = pdg["number_of_decays"] -event_stack = 1000000 -# nevents *= 41 -# zfit.settings.set_verbosity(10) - -mi = 0.0 -ma = 1e-3 -ste = 11 - -BR_steps = np.linspace(mi, ma, ste) - -Ctt_steps = np.sqrt(BR_steps/4.2*1000) - -total_samp = [] - -start = time.time() - -Nll_list = [] - -sampler = total_f.create_sampler(n=nevents) - -__ = 0 - - -#----------------------------------------------------- - -if not load: - - for Ctt_step in Ctt_steps: - - __ += 1 - - newset = True - - for floaty in [True, False]: - - Ctt.floating = floaty - - Nll_list.append([]) - - if bo5: - - while len(Nll_list[-1])/bo5_set < nr_of_toys: - - print('Step: {0}/{1}'.format(__, ste)) - - print('Current Ctt: {0}'.format(Ctt_step)) - print('Ctt floating: {0}'.format(floaty)) - - print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) - - reset_param_values() - - if floaty: - Ctt.set_value(Ctt_step) - else: - Ctt.set_value(0.0) - - if newset: - sampler.resample(n=nevents) - s = sampler.unstack_x() - total_samp = zfit.run(s) - calls = 0 - c = 1 - newset = False - - - data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) - - ### Fit data - - for param in total_f_fit.get_dependents(): - param.randomize() - - nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - - minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) - # minimizer._use_tfgrad = False - result = minimizer.minimize(nll) - - # print("Function minimum:", result.fmin) - # print("Hesse errors:", result.hesse()) - - params = result.params - - if result.converged: - Nll_list[-1].append(result.fmin) - - else: - - while len(Nll_list[-1]) < nr_of_toys: - - print('Step: {0}/{1}'.format(__, ste)) - - print('Current Ctt: {0}'.format(Ctt_step)) - print('Ctt floating: {0}'.format(floaty)) - - print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) - - reset_param_values() - - if floaty: - Ctt.set_value(Ctt_step) - else: - Ctt.set_value(0.0) - - if floaty: - sampler.resample(n=nevents) - s = sampler.unstack_x() - total_samp = zfit.run(s) - calls = 0 - c = 1 - - - data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) - - ### Fit data - - for param in total_f_fit.get_dependents(): - param.randomize() - - nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - - minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) - # minimizer._use_tfgrad = False - result = minimizer.minimize(nll) - - # print("Function minimum:", result.fmin) - # print("Hesse errors:", result.hesse()) - - params = result.params - - if result.converged: - Nll_list[-1].append(result.fmin) - - _t = int(time.time()-start) - - print('Time Taken: {}'.format(display_time(int(_t)))) - - print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) - - -# In[48]: - - -if load: - Nll_list = [] - CLs_values = [] - - _dir = 'data/CLs/finished/f1d1' - - jobs = os.listdir(_dir) - - for s in range(ste): - CLs_values.append([]) - - for s in range(2*ste): - Nll_list.append([]) - - for job in jobs: - if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): - print(job) - continue - - with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: - _Nll_list = pkl.load(input_file) - - if bo5: - for s in range(2*ste): - Nll_list[s].append(np.min(_Nll_list[s])) - else: - for s in range(2*ste): - Nll_list[s].extend(_Nll_list[s]) - - with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: - _CLs_values = pkl.load(input_file) - - for s in range(ste): - CLs_values[s].extend(_CLs_values[s]) - - print(np.shape(Nll_list)) - - -# In[50]: - - -dirName = 'data/CLs' - -# if bo5 and not load: -# for s in range(2*ste): -# Nll_list[s] = [np.min(Nll_list[s])] - -if bo5: - CLs_values= [] - for i in range(int(len(Nll_list)/2)): - CLs_values.append([]) - for j in range(len(Nll_list[0])): - CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) - - -if not load: - - CLs_values = [] - - for i in range(int(len(Nll_list)/2)): - CLs_values.append([]) - for j in range(nr_of_toys): - CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) - - if not os.path.exists(dirName): - os.mkdir(dirName) - print("Directory " , dirName , " Created ") - - with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: - pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) - - with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: - pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) - - -# In[51]: - - -# print(CLs_values) -print(Nll_list) - - -# ## Plot - -# In[52]: - - -l = [] - -for i in range(len(CLs_values)): - plt.clf() - plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) - plt.hist(CLs_values[0], bins = 100, label = 'Ctt fixed to 0') - plt.hist(CLs_values[i], bins = 100, label = 'Ctt floating') - plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=0.7, linestyle = 'dotted') - plt.legend() - plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) - - l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) - - -# In[53]: - - -for s in range(len(l)): - print('BR: {}'.format(BR_steps[s])) - print(2*l[s]/len(CLs_values[0])) - print() - - -# In[54]: - - -# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) - - -# In[ ]: - - - - diff --git a/data/CLs/finished/f1d1/2254886/test.png b/data/CLs/finished/f1d1/2254886/test.png deleted file mode 100644 index 1455457..0000000 --- a/data/CLs/finished/f1d1/2254886/test.png +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254891/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/2254891/__pycache__/helperfunctions.cpython-37.pyc deleted file mode 100644 index ac2b0f3..0000000 --- a/data/CLs/finished/f1d1/2254891/__pycache__/helperfunctions.cpython-37.pyc +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254891/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/2254891/__pycache__/pdg_const.cpython-37.pyc deleted file mode 100644 index 499d38c..0000000 --- a/data/CLs/finished/f1d1/2254891/__pycache__/pdg_const.cpython-37.pyc +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254891/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/2254891/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl deleted file mode 100644 index ceaff27..0000000 --- a/data/CLs/finished/f1d1/2254891/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254891/data/CLs/0.0-0.001_11s--CLs_list.pkl b/data/CLs/finished/f1d1/2254891/data/CLs/0.0-0.001_11s--CLs_list.pkl deleted file mode 100644 index f0e7330..0000000 --- a/data/CLs/finished/f1d1/2254891/data/CLs/0.0-0.001_11s--CLs_list.pkl +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254891/helperfunctions.py b/data/CLs/finished/f1d1/2254891/helperfunctions.py deleted file mode 100644 index 88e120f..0000000 --- a/data/CLs/finished/f1d1/2254891/helperfunctions.py +++ /dev/null @@ -1,33 +0,0 @@ -# some helperfunctions - -import matplotlib -matplotlib.use("agg") -import matplotlib.pyplot as plt - -#Dislpay time (e.g. while generating points) - -display_intervals = ( - ('w', 604800), # 60 * 60 * 24 * 7 - ('d', 86400), # 60 * 60 * 24 - ('h', 3600), # 60 * 60 - ('min', 60), - ('s', 1), - ) - -def display_time(seconds, granularity=2): - result = [] - - for name, count in display_intervals: - value = seconds // count - if value: - seconds -= value * count - if value == 1: - name = name.rstrip('s') - result.append("{} {}".format(value, name)) - return ', '.join(result[:granularity]) - -def prepare_plot(title): - plt.title(title) - plt.grid() - plt.legend(loc = 'best') - plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/2254891/pdg_const.py b/data/CLs/finished/f1d1/2254891/pdg_const.py deleted file mode 100644 index 6645dd7..0000000 --- a/data/CLs/finished/f1d1/2254891/pdg_const.py +++ /dev/null @@ -1,226 +0,0 @@ -pdg = { - - - ###Particle masses### - - "mbstar" : 5415.4, - "mbstar0" : 5711.0, - "B0_M" : 5279.5, - "Bs_M" : 5366.7, - "Bplus_M" : 5279.3, - "Lb_M" : 5619.4, - "D0_M" : 1864.8, - "Dst_M" : 2010, - "pi_M" : 139.6, - "Jpsi_M" : 3096.9, - "Psi2s_M" : 3685.6, - "kaon_M" : 493.7, - "Ks_M" : 497.6, - "phi_M" : 1019.5, - "rho_M" : 775.26, - "rho_width" : 149.1, - "omega_M" : 782.65, - "omega_width" : 8.49, - - "muon_M" : 105.7, - "tau_M": 1776.86, - - "squark_M" : 95.0, - "bquark_M" : 4180.0, - "cquark_M" : 1275.0, - - "Bplus_tau" : 1.638e-12, - - ###Wilson coefficients### - - "C1" : -0.257, - "C2" : 1.009, - "C3" : -0.005, - "C4" : -0.078, - - "C7eff" : -0.306, - "C9eff" : 4.211, - "C10eff" : -4.103, - -# "C7eff": 0.0, -# "C9eff": 0.0, -# "C10eff": 0.0, - - ###Other constants - - "GF" : 1.1663787e-5, - "alpha_ew" : 1.0/137.0, - "Vts" : 0.0394, - "Vtb" : 1.019, - "number_of_decays": 5404696, - - #Formfactor z coefficients - - #"b0" : [0.285, 0.19, -0.17], - #"bplus" : [0.437, -1.41, -2.5], - #"bT" : [0.440, -1.47, -2.7] - - "b0" : [0.292, 0.281, 0.150], - "bplus" : [0.466, -0.885, -0.213], - "bT" : [0.460, -1.089, -1.114], - - "NR_BR": 4.37e-7, - "NR_auc": 0.00133, - - #Resonances format(mass, width, phase, scale) - - # pre scaling - -# "rho": (775.26, 149.0, -0.35, 1.0), - -# "omega": (782.7, 8.5, 0.26, 1.0), - -# "phi": (1019.46, 4.25, 0.5, 1.0), - -# "jpsi": (3096.0, 0.09, -1.5, 2e-2), -# "jpsi_auc": 0.2126825758464027, - -# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), -# "psi2s_auc": 2.802257483178487e-10, - -# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), - -# "p4040": (4039.0, 80.0, -2.52, 2.0), - -# "p4160": (4191.0, 70.0, -1.9, 2.2), - -# "p4415": (4421.0, 62.0, -2.52, 1.0), - - - # after scaling (Phase combination --) - - -# "rho": (743.2, 149.0, -0.22, 1.05), - -# "omega": (782.7, 8.5, 0.38, 6.8), - -# "phi": (1013.5, 4.25, 0.62, 19.2), - -# "jpsi": (3096.1, 0.09, 1.63, 9897.0), -# "jpsi_auc": 0.2126825758464027, -# "jpsi_phase_unc": 0.05, - -# "psi2s": (3686.0, 0.3, 1.8, 1396.0), -# "psi2s_auc": 0.0151332263, -# "psi2s_phase_unc": 0.1, - -# "p3770": (3773.0, 27.2, -2.95, 2.5), - -# "p4040": (4039.0, 80.0, -2.75, 1.01), - -# "p4160": (4191.0, 70.0, -2.28, 2.2), - -# "p4415": (4421.0, 62.0, -2.31, 1.24), - - # Phase combination of paper ++ - -# "rho": (743.2, 149.0, -0.35, 1.05), - -# "omega": (782.7, 8.5, 0.26, 6.8), - -# "phi": (1013.5, 4.25, 0.47, 19.2), - -# "jpsi": (3096.1, 0.09, -1.66, 9897.0), -# "jpsi_auc": 0.2126825758464027, -# "jpsi_phase_unc": 0.05, - -# "psi2s": (3686.0, 0.3, -1.93, 1396.0), -# "psi2s_auc": 0.0151332263, -# "psi2s_phase_unc": 0.1, - -# "p3770": (3773.0, 27.2, -2.13, 2.5), - -# "p4040": (4039.0, 80.0, -2.52, 1.01), - -# "p4160": (4191.0, 70.0, -1.90, 2.2), - -# "p4415": (4421.0, 62.0, -2.52, 1.24), - - # Phase combination of paper +- - - # "rho": (743.2, 149.0, -0.26, 1.05), - # - # "omega": (782.7, 8.5, 0.35, 6.8), - # - # "phi": (1013.5, 4.25, 0.58, 19.2), - # - # "jpsi": (3096.1, 0.09, 1.47, 9897.0), - # "jpsi_auc": 0.2126825758464027, - # "jpsi_phase_unc": 0.05, - # - # "psi2s": (3686.0, 0.3, -2.21, 1396.0), - # "psi2s_auc": 0.0151332263, - # "psi2s_phase_unc": 0.1, - # - # "p3770": (3773.0, 27.2, -2.140, 2.5), - # - # "p4040": (4039.0, 80.0, -2.64, 1.01), - # - # "p4160": (4191.0, 70.0, -2.11, 2.2), - # - # "p4415": (4421.0, 62.0, -2.42, 1.24), - - # Phase combination of paper -+ - - "rho": (743.2, 149.0, -0.30, 1.05), - - "omega": (782.7, 8.5, 0.30, 6.8), - - "phi": (1013.5, 4.25, 0.51, 19.2), - - "jpsi": (3096.1, 0.09, -1.5, 9897.0), - "jpsi_auc": 0.2126825758464027, - "jpsi_phase_unc": 0.05, - - "psi2s": (3686.0, 0.3, 2.08, 1396.0), - "psi2s_auc": 0.0151332263, - "psi2s_phase_unc": 0.1, - - "p3770": (3773.0, 27.2, -2.89, 2.5), - - "p4040": (4039.0, 80.0, -2.69, 1.01), - - "p4160": (4191.0, 70.0, -2.13, 2.2), - - "p4415": (4421.0, 62.0, -2.43, 1.24), - - - # zeroing resonances - -# "rho": (775.26, 149.0, -0.35, 0.0), -# "omega": (782.7, 8.5, 0.26, 0.0), -# "phi": (1019.46, 4.25, 0.5, 0.0), -# "jpsi": (3096.0, 0.09, -1.5, 0.0), -# "psi2s": (3686.0, 0.3, -1.5, 0.0), -# "p3770": (3773.0, 27.2, -2.13, 0.0), -# "p4040": (4039.0, 80.0, -2.52, 0.0), -# "p4160": (4147.0, 22.0, -1.9, 0.0), -# "p4415": (4421.0, 62.0, -2.52, 0.0), - - # 2P contributions format(mass, amp, phase) - -# "D_bar": ( - - #general - - "rho_BR": 1.7e-10, - "omega_BR": 4.9e-10, - "phi_BR": 2.5e-9, - "jpsi_BR": 6.02e-5, - "psi2s_BR": 4.97e-6, - "p3770_BR": 1.38e-9, - "p4040_BR": 4.2e-10, - "p4160_BR": 2.6e-9, - "p4415_BR": 6.1e-10, - -# Estimates - "Dbar_scale": 1.46, #with phase = pi - - "DDstar_scale": 2.41, #with phase = pi - - } diff --git a/data/CLs/finished/f1d1/2254891/raremodel-nb1.py b/data/CLs/finished/f1d1/2254891/raremodel-nb1.py deleted file mode 100644 index 1a5d9be..0000000 --- a/data/CLs/finished/f1d1/2254891/raremodel-nb1.py +++ /dev/null @@ -1,1939 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -# # Import - -# In[1]: - - -import os - -# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" - -import numpy as np -from pdg_const import pdg -import matplotlib -import matplotlib.pyplot as plt -import pickle as pkl -import sys -import time -from helperfunctions import display_time, prepare_plot -import cmath as c -import scipy.integrate as integrate -from scipy.optimize import fminbound -from array import array as arr -import collections -from itertools import compress -import tensorflow as tf -import zfit -from zfit import ztf -# from IPython.display import clear_output -import os -import tensorflow_probability as tfp -tfd = tfp.distributions - - -# In[2]: - - -# chunksize = 10000 -# zfit.run.chunking.active = True -# zfit.run.chunking.max_n_points = chunksize - - -# # Build model and graphs -# ## Create graphs - -# In[ ]: - - - - - -# In[3]: - - -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 - #check if subscript is viable - - if subscript != "0" and subscript != "+" and subscript != "T": - raise ValueError('Wrong subscript entered, choose either 0, + or T') - - #get constants - - mK = ztf.constant(pdg['Ks_M']) - mbstar0 = ztf.constant(pdg["mbstar0"]) - mbstar = ztf.constant(pdg["mbstar"]) - - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mB = ztf.constant(pdg['Bplus_M']) - - #N comes from derivation in paper - - N = 3 - - #some helperfunctions - - tpos = (mB - mK)**2 - tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 - - z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) - z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) - z = tf.divide(z_oben, z_unten) - - #calculate f0 - - if subscript == "0": - prefactor = 1/(1 - q2/(mbstar0**2)) - _sum = 0 - b0 = [b0_0, b0_1, b0_2] - - for i in range(N): - _sum += b0[i]*(tf.pow(z,i)) - - return ztf.to_complex(prefactor * _sum) - - #calculate f+ or fT - - else: - prefactor = 1/(1 - q2/(mbstar**2)) - _sum = 0 - - if subscript == "T": - bT = [bT_0, bT_1, bT_2] - for i in range(N): - _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) - else: - bplus = [bplus_0, bplus_1, bplus_2] - for i in range(N): - _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) - - return ztf.to_complex(prefactor * _sum) - -def resonance(q, _mass, width, phase, scale): - - q2 = tf.pow(q, 2) - - mmu = ztf.constant(pdg['muon_M']) - - p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) - - p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) - - gamma_j = tf.divide(p, q) * _mass * width / p0 - - #Calculate the resonance - - _top = tf.complex(_mass * width, ztf.constant(0.0)) - - _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) - - com = _top/_bottom - - #Rotate by the phase - - r = ztf.to_complex(scale*tf.abs(com)) - - _phase = tf.angle(com) - - _phase += phase - - com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) - - return com - - -def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): - - GF = ztf.constant(pdg['GF']) - alpha_ew = ztf.constant(pdg['alpha_ew']) - Vtb = ztf.constant(pdg['Vtb']) - Vts = ztf.constant(pdg['Vts']) - C10eff = ztf.constant(pdg['C10eff']) - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mK = ztf.constant(pdg['Ks_M']) - mB = ztf.constant(pdg['Bplus_M']) - - q2 = tf.pow(q, 2) - - #Some helperfunctions - - beta = 1. - 4. * mmu**2. / q2 - - 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.) - - #prefactor in front of whole bracket - - prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) - - #left term in bracket - - 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) - - #middle term in bracket - - _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) - - _under = q2 * mB**2. - - 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) - - #Note sqrt(q2) comes from derivation as we use q2 and plot q - - return prefactor1 * (bracket_left + bracket_middle) * 2 * q - -def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): - - q2 = tf.pow(q, 2) - - GF = ztf.constant(pdg['GF']) - alpha_ew = ztf.constant(pdg['alpha_ew']) - Vtb = ztf.constant(pdg['Vtb']) - Vts = ztf.constant(pdg['Vts']) - C7eff = ztf.constant(pdg['C7eff']) - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mK = ztf.constant(pdg['Ks_M']) - mB = ztf.constant(pdg['Bplus_M']) - - #Some helperfunctions - - beta = 1. - 4. * mmu**2. / q2 - - 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) - - #prefactor in front of whole bracket - - prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) - - #right term in bracket - - prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) - - 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) - - bracket_right = prefactor2 * abs_bracket - - #Note sqrt(q2) comes from derivation as we use q2 and plot q - - return prefactor1 * bracket_right * 2 * q - -def c9eff(q, funcs): - - C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) - - c9 = C9eff_nr + funcs - - return c9 - - -# In[4]: - - -def G(y): - - def inner_rect_bracket(q): - return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) - - def inner_right(q): - return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) - - big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) - - return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket - -def h_S(m, q): - - 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))) - -def h_P(m, q): - - 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) - -def two_p_ccbar(mD, m_D_bar, m_D_star, q): - - - #Load constants - nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) - nu_D = ztf.to_complex(pdg["nu_D"]) - nu_D_star = ztf.to_complex(pdg["nu_D_star"]) - - phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) - phase_D = ztf.to_complex(pdg["phase_D"]) - phase_D_star = ztf.to_complex(pdg["phase_D_star"]) - - #Calculation - left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) - - right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) - - right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) - - return left_part + right_part_D + right_part_D_star - - -# ## Build pdf - -# In[5]: - - -class total_pdf_cut(zfit.pdf.ZPDF): - _N_OBS = 1 # dimension, can be omitted - _PARAMS = ['b0_0', 'b0_1', 'b0_2', - 'bplus_0', 'bplus_1', 'bplus_2', - 'bT_0', 'bT_1', 'bT_2', - 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', - 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', - 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', - 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', - 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', - 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', - 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', - 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', - 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', - 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', - 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', - 'tau_mass', 'C_tt'] -# the name of the parameters - - def _unnormalized_pdf(self, x): - - x = x.unstack_x() - - b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] - bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] - bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] - - def rho_res(q): - return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], - phase = self.params['rho_phase'], width = self.params['rho_width']) - - def omega_res(q): - return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], - phase = self.params['omega_phase'], width = self.params['omega_width']) - - def phi_res(q): - return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], - phase = self.params['phi_phase'], width = self.params['phi_width']) - - def jpsi_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], - scale = self.params['jpsi_scale'], - phase = self.params['jpsi_phase'], - width = self.params['jpsi_width']) - def psi2s_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], - scale = self.params['psi2s_scale'], - phase = self.params['psi2s_phase'], - width = self.params['psi2s_width']) - def p3770_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], - scale = self.params['p3770_scale'], - phase = self.params['p3770_phase'], - width = self.params['p3770_width']) - - def p4040_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], - scale = self.params['p4040_scale'], - phase = self.params['p4040_phase'], - width = self.params['p4040_width']) - - def p4160_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], - scale = self.params['p4160_scale'], - phase = self.params['p4160_phase'], - width = self.params['p4160_width']) - - def p4415_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], - scale = self.params['p4415_scale'], - phase = self.params['p4415_phase'], - width = self.params['p4415_width']) - - def P2_D(q): - 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)) - 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))) - return Dbar_contrib + DDstar_contrib - - def ttau_cusp(q): - 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))) - - - 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) - - vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - tot = vec_f + axiv_nr - - #Cut out jpsi and psi2s - - tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) - - tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) - - return tot - -class total_pdf_full(zfit.pdf.ZPDF): - _N_OBS = 1 # dimension, can be omitted - _PARAMS = ['b0_0', 'b0_1', 'b0_2', - 'bplus_0', 'bplus_1', 'bplus_2', - 'bT_0', 'bT_1', 'bT_2', - 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', - 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', - 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', - 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', - 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', - 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', - 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', - 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', - 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', - 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', - 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', - 'tau_mass', 'C_tt'] -# the name of the parameters - - def _unnormalized_pdf(self, x): - - x = x.unstack_x() - - b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] - bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] - bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] - - def rho_res(q): - return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], - phase = self.params['rho_phase'], width = self.params['rho_width']) - - def omega_res(q): - return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], - phase = self.params['omega_phase'], width = self.params['omega_width']) - - def phi_res(q): - return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], - phase = self.params['phi_phase'], width = self.params['phi_width']) - - def jpsi_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], - scale = self.params['jpsi_scale'], - phase = self.params['jpsi_phase'], - width = self.params['jpsi_width']) - def psi2s_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], - scale = self.params['psi2s_scale'], - phase = self.params['psi2s_phase'], - width = self.params['psi2s_width']) - def p3770_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], - scale = self.params['p3770_scale'], - phase = self.params['p3770_phase'], - width = self.params['p3770_width']) - - def p4040_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], - scale = self.params['p4040_scale'], - phase = self.params['p4040_phase'], - width = self.params['p4040_width']) - - def p4160_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], - scale = self.params['p4160_scale'], - phase = self.params['p4160_phase'], - width = self.params['p4160_width']) - - def p4415_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], - scale = self.params['p4415_scale'], - phase = self.params['p4415_phase'], - width = self.params['p4415_width']) - - def P2_D(q): - 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)) - 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))) - return Dbar_contrib + DDstar_contrib - - def ttau_cusp(q): - 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))) - - - 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) - - vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - tot = vec_f + axiv_nr - - #Cut out jpsi and psi2s - -# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) - -# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) - - return tot - - -# ## Setup parameters - -# In[6]: - - -# formfactors - -b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) - -bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) -bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) -bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) - -bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) - - -#rho - -rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] - -rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) -rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) -rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#omega - -omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] - -omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) -omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) -omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - - -#phi - -phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] - -phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) -phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) -phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#jpsi - -jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] - -jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) -jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) -jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi2s - -psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] - -psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) -psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) -psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(3770) - -p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] - -p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) -p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) -p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4040) - -p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] - -p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) -p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) -p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4160) - -p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] - -p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) -p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) -p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4415) - -p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] - -p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) -p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) -p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - - -# ## Dynamic generation of 2 particle contribution - -# In[7]: - - -m_c = 1300 - -Dbar_phase = 0.0 -DDstar_phase = 0.0 -Dstar_mass = pdg['Dst_M'] -Dbar_mass = pdg['D0_M'] -D_mass = pdg['D0_M'] - -Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) -Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) -Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) -DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) -Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) -D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) -DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) - - -# ## Tau parameters - -# In[8]: - - -tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) -Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) - - -# ## Load data - -# In[9]: - - -x_min = 2*pdg['muon_M'] -x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) - -# # Full spectrum - -obs_toy = zfit.Space('q', limits = (x_min, x_max)) - -# Jpsi and Psi2s cut out - -obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) -obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) -obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) - -obs_fit = obs1 + obs2 + obs3 - -# 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: -# part_set = pkl.load(input_file) - -# x_part = part_set['x_part'] - -# x_part = x_part.astype('float64') - -# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) - - -# ## Setup pdf - -# In[10]: - - -total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, - psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, - p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, - p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, - p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, - p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, - rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, - omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, - phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, - Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, - Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, - tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, - bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, - bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) - -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, - psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, - p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, - p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, - p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, - p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, - rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, - omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, - phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, - Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, - Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, - tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, - bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, - bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) - -# print(total_pdf.obs) - -# print(calcs_test) - -# for param in total_f.get_dependents(): -# print(zfit.run(param)) - - -# In[11]: - - -total_f_fit.normalization(obs_toy) - - -# ## Test if graphs actually work and compute values - -# In[12]: - - -# def total_test_tf(xq): - -# def jpsi_res(q): -# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) - -# def psi2s_res(q): -# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) - -# def cusp(q): -# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) - -# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) - -# vec_f = vec(xq, funcs) - -# axiv_nr = axiv_nonres(xq) - -# tot = vec_f + axiv_nr - -# return tot - -# def jpsi_res(q): -# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) - -# calcs = zfit.run(total_test_tf(x_part)) - -test_q = np.linspace(x_min, x_max, int(2e6)) - -probs = total_f_fit.pdf(test_q, norm_range=False) - -calcs_test = zfit.run(probs) -# res_y = zfit.run(jpsi_res(test_q)) -# b0 = [b0_0, b0_1, b0_2] -# bplus = [bplus_0, bplus_1, bplus_2] -# bT = [bT_0, bT_1, bT_2] -# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) -# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) -# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) - - -# In[13]: - - -plt.clf() -# plt.plot(x_part, calcs, '.') -plt.plot(test_q, calcs_test, label = 'pdf') -# plt.plot(test_q, f0_y, label = '0') -# plt.plot(test_q, fT_y, label = 'T') -# plt.plot(test_q, fplus_y, label = '+') -# plt.plot(test_q, res_y, label = 'res') -plt.legend() -plt.ylim(0.0, 1.5e-6) -# plt.yscale('log') -# plt.xlim(770, 785) -plt.savefig('test.png') -# print(jpsi_width) - - -# In[14]: - - - - -# probs = mixture.prob(test_q) -# probs_np = zfit.run(probs) -# probs_np *= np.max(calcs_test) / np.max(probs_np) -# plt.figure() -# plt.semilogy(test_q, probs_np,label="importance sampling") -# plt.semilogy(test_q, calcs_test, label = 'pdf') - - -# In[15]: - - -# 0.213/(0.00133+0.213+0.015) - - -# ## Adjust scaling of different parts - -# In[16]: - - -total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) -# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) -# inte_fl = zfit.run(inte) -# print(inte_fl/4500) -# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) - - -# In[17]: - - -# # print("jpsi:", inte_fl) -# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - -# # print("psi2s:", inte_fl) -# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - -# name = "phi" - -# print(name+":", inte_fl) -# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - - -# print(x_min) -# print(x_max) -# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) -# total_f.update_integration_options(mc_sampler=lambda dim, num_results, -# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), -# draws_per_dim=1000000) -# # _ = [] - -# # for i in range(10): - -# # inte = total_f.integrate(limits = (x_min, x_max)) -# # inte_fl = zfit.run(inte) -# # print(inte_fl) -# # _.append(inte_fl) - -# # print("mean:", np.mean(_)) - -# _ = time.time() - -# inte = total_f.integrate(limits = (x_min, x_max)) -# inte_fl = zfit.run(inte) -# print(inte_fl) -# print("Time taken: {}".format(display_time(int(time.time() - _)))) - -# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) -# print(0.25**2*4.2/1000) - - -# # Sampling -# ## Mixture distribution for sampling - -# In[18]: - - - - -# print(list_of_borders[:9]) -# print(list_of_borders[-9:]) - - -class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): - def __call__(self, limits, dtype, n_to_produce): - # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) - low, high = limits.limit1d - low = tf.cast(low, dtype=dtype) - high = tf.cast(high, dtype=dtype) -# uniform = tfd.Uniform(low=low, high=high) -# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) -# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) - -# list_of_borders = [] -# _p = [] -# splits = 10 - -# _ = np.linspace(x_min, x_max, splits) - -# for i in range(splits): -# list_of_borders.append(tf.constant(_[i], dtype=dtype)) -# _p.append(tf.constant(1/splits, dtype=dtype)) - -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), -# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], -# high=list_of_borders[-(splits-1):])) - mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), - tf.constant(0.93, dtype=dtype), - tf.constant(0.05, dtype=dtype), - tf.constant(0.065, dtype=dtype), - tf.constant(0.04, dtype=dtype), - tf.constant(0.05, dtype=dtype)]), - components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), - tf.constant(3090, dtype=dtype), - tf.constant(3681, dtype=dtype), - tf.constant(3070, dtype=dtype), - tf.constant(1000, dtype=dtype), - tf.constant(3660, dtype=dtype)], - high=[tf.constant(x_max, dtype=dtype), - tf.constant(3102, dtype=dtype), - tf.constant(3691, dtype=dtype), - tf.constant(3110, dtype=dtype), - tf.constant(1040, dtype=dtype), - tf.constant(3710, dtype=dtype)])) -# dtype = tf.float64 -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), -# tf.constant(0.90, dtype=dtype), -# tf.constant(0.02, dtype=dtype), -# tf.constant(0.07, dtype=dtype), -# tf.constant(0.02, dtype=dtype)]), -# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), -# tf.constant(3089, dtype=dtype), -# tf.constant(3103, dtype=dtype), -# tf.constant(3681, dtype=dtype), -# tf.constant(3691, dtype=dtype)], -# high=[tf.constant(3089, dtype=dtype), -# tf.constant(3103, dtype=dtype), -# tf.constant(3681, dtype=dtype), -# tf.constant(3691, dtype=dtype), -# tf.constant(x_max, dtype=dtype)])) -# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) -# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) - sample = mixture.sample((n_to_produce, 1)) -# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) - weights = mixture.prob(sample)[:,0] -# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) - # sample = tf.expand_dims(sample, axis=-1) -# print(sample, weights) - -# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) - weights_max = None - thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) - return sample, thresholds, weights, weights_max, n_to_produce - - -# In[19]: - - -# total_f._sample_and_weights = UniformSampleAndWeights - - -# In[20]: - - -# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) - - -# In[21]: - - -# zfit.settings.set_verbosity(10) - - -# In[22]: - - -# # zfit.run.numeric_checks = False - -# nr_of_toys = 1 -# nevents = int(pdg["number_of_decays"]) -# nevents = pdg["number_of_decays"] -# event_stack = 1000000 -# # zfit.settings.set_verbosity(10) -# calls = int(nevents/event_stack + 1) - -# total_samp = [] - -# start = time.time() - -# sampler = total_f.create_sampler(n=event_stack) - -# for toy in range(nr_of_toys): - -# dirName = 'data/zfit_toys/toy_{0}'.format(toy) - -# if not os.path.exists(dirName): -# os.mkdir(dirName) -# print("Directory " , dirName , " Created ") - -# for call in range(calls): - -# sampler.resample(n=event_stack) -# s = sampler.unstack_x() -# sam = zfit.run(s) -# # clear_output(wait=True) - -# c = call + 1 - -# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) - -# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: -# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) - - -# In[23]: - - -# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: -# sam = pkl.load(input_file) -# print(sam[:10]) - -# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: -# sam2 = pkl.load(input_file) -# print(sam2[:10]) - -# print(np.sum(sam-sam2)) - - -# In[24]: - - -# print("Time to generate full toy: {} s".format(int(time.time()-start))) - -# total_samp = [] - -# for call in range(calls): -# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: -# sam = pkl.load(input_file) -# total_samp = np.append(total_samp, sam) - -# total_samp = total_samp.astype('float64') - -# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) - -# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) - -# print(total_samp[:nevents].shape) - - -# In[25]: - - -# plt.clf() - -# bins = int((x_max-x_min)/7) - -# # calcs = zfit.run(total_test_tf(samp)) -# print(total_samp[:nevents].shape) - -# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') -# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') - -# # plt.plot(sam, calcs, '.') -# # plt.plot(test_q, calcs_test) -# # plt.yscale('log') -# plt.ylim(0, 200) -# # plt.xlim(3080, 3110) - -# plt.legend() - -# plt.savefig('test2.png') - - -# In[26]: - - -# sampler = total_f.create_sampler(n=nevents) -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) - -# # for param in pdf.get_dependents(): -# # param.set_value(initial_value) - -# sampler.resample(n=nevents) - -# # Randomise initial values -# # for param in pdf.get_dependents(): -# # param.set_value(random value here) - -# # Minimise the NLL -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) -# minimum = minimizer.minimize(nll) - - -# In[27]: - - -# jpsi_width - - -# In[28]: - - -# plt.hist(sample, weights=1 / prob(sample)) - - -# # Fitting - -# In[29]: - - -# start = time.time() - -# for param in total_f.get_dependents(): -# param.randomize() - -# # for param in total_f.get_dependents(): -# # print(zfit.run(param)) - -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# # param_errors = result.error() - -# # for var, errors in param_errors.items(): -# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) - -# print("Function minimum:", result.fmin) -# # print("Results:", result.params) -# print("Hesse errors:", result.hesse()) - - -# In[30]: - - -# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) - -# # probs = total_f.pdf(test_q) - -# calcs_test = zfit.run(probs) -# res_y = zfit.run(jpsi_res(test_q)) - - -# In[31]: - - -# plt.clf() -# # plt.plot(x_part, calcs, '.') -# plt.plot(test_q, calcs_test, label = 'pdf') -# # plt.plot(test_q, res_y, label = 'res') -# plt.legend() -# plt.ylim(0.0, 10e-6) -# # plt.yscale('log') -# # plt.xlim(3080, 3110) -# plt.savefig('test3.png') -# # print(jpsi_width) - - -# In[32]: - - -# _tot = 4.37e-7+6.02e-5+4.97e-6 -# _probs = [] -# _probs.append(6.02e-5/_tot) -# _probs.append(4.97e-6/_tot) -# _probs.append(4.37e-7/_tot) -# print(_probs) - - -# In[33]: - - -# dtype = 'float64' -# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), -# tf.constant(0.917, dtype=dtype), -# tf.constant(0.076, dtype=dtype)]), -# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), -# tf.constant(3080, dtype=dtype), -# tf.constant(3670, dtype=dtype)], -# high=[tf.constant(x_max, dtype=dtype), -# tf.constant(3112, dtype=dtype), -# tf.constant(3702, dtype=dtype)])) -# # for i in range(10): -# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) - - -# In[34]: - - -# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) -# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) - - -# In[35]: - - -# def jpsi_res(q): -# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, -# phase = jpsi_phase, width = jpsi_width) - -# def psi2s_res(q): -# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, -# phase = psi2s_phase, width = psi2s_width) - -# def p3770_res(q): -# return resonance(q, _mass = p3770_mass, scale = p3770_scale, -# phase = p3770_phase, width = p3770_width) - -# def p4040_res(q): -# return resonance(q, _mass = p4040_mass, scale = p4040_scale, -# phase = p4040_phase, width = p4040_width) - -# def p4160_res(q): -# return resonance(q, _mass = p4160_mass, scale = p4160_scale, -# phase = p4160_phase, width = p4160_width) - -# def p4415_res(q): -# return resonance(q, _mass = p4415_mass, scale = p4415_scale, -# phase = p4415_phase, width = p4415_width) - - -# In[36]: - - -# 0.15**2*4.2/1000 -# result.hesse() - - -# ## Constraints - -# In[37]: - - -# 1. Constraint - Real part of sum of Psi contrib and D contribs - -sum_list = [] - -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)))) -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)))) -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)))) -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)))) -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)))) -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)))) -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))))) -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)))) - -sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) - -for part in sum_list: - sum_ru_1 += part - -sum_1 = tf.math.real(sum_ru_1) -# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), -# sigma = ztf.constant(2.2*10**-8)) - -constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) - -# 2. Constraint - Abs. of sum of Psi contribs and D contribs - -sum_2 = tf.abs(sum_ru_1) -constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) - -# 3. Constraint - Maximum eta of D contribs - -constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) - -constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) - -# 4. Constraint - Formfactor multivariant gaussian covariance fplus - -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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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.)]] - -def triGauss(val1,val2,val3,m = Cov_matrix): - - mean1 = ztf.constant(0.466) - mean2 = ztf.constant(-0.885) - mean3 = ztf.constant(-0.213) - sigma1 = ztf.constant(0.014) - sigma2 = ztf.constant(0.128) - sigma3 = ztf.constant(0.548) - x1 = (val1-mean1)/sigma1 - x2 = (val2-mean2)/sigma2 - x3 = (val3-mean3)/sigma3 - rho12 = m[0][1] - rho13 = m[0][2] - rho23 = m[1][2] - 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)) - d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) - - fcn = -w/d - chisq = -2*fcn - return chisq - -constraint4 = triGauss(bplus_0, bplus_1, bplus_2) - -# mean1 = ztf.constant(0.466) -# mean2 = ztf.constant(-0.885) -# mean3 = ztf.constant(-0.213) -# sigma1 = ztf.constant(0.014) -# sigma2 = ztf.constant(0.128) -# sigma3 = ztf.constant(0.548) -# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) -# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) -# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) - -# 5. Constraint - Abs. of sum of light contribs - -sum_list_5 = [] - -sum_list_5.append(rho_s*rho_w/rho_m) -sum_list_5.append(omega_s*omega_w/omega_m) -sum_list_5.append(phi_s*phi_w/phi_m) - - -sum_ru_5 = ztf.constant(0.0) - -for part in sum_list_5: - sum_ru_5 += part - -constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) - -# 6. Constraint on phases of Jpsi and Psi2s for cut out fit - - -# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), -# sigma = ztf.constant(jpsi_phase)) -# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), -# sigma = ztf.constant(psi2s_phase)) - -constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) -constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) - -# 7. Constraint on Ctt with higher limits - -constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) - -constraint7dtype = tf.float64 - -# zfit.run(constraint6_0) - -# ztf.convert_to_tensor(constraint6_0) - -#List of all constraints - -constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, - constraint6_0, constraint6_1]#, constraint7] - - -# ## Reset params - -# In[38]: - - -def reset_param_values(): - jpsi_m.set_value(jpsi_mass) - jpsi_s.set_value(jpsi_scale) - jpsi_p.set_value(jpsi_phase) - jpsi_w.set_value(jpsi_width) - psi2s_m.set_value(psi2s_mass) - psi2s_s.set_value(psi2s_scale) - psi2s_p.set_value(psi2s_phase) - psi2s_w.set_value(psi2s_width) - p3770_m.set_value(p3770_mass) - p3770_s.set_value(p3770_scale) - p3770_p.set_value(p3770_phase) - p3770_w.set_value(p3770_width) - p4040_m.set_value(p4040_mass) - p4040_s.set_value(p4040_scale) - p4040_p.set_value(p4040_phase) - p4040_w.set_value(p4040_width) - p4160_m.set_value(p4160_mass) - p4160_s.set_value(p4160_scale) - p4160_p.set_value(p4160_phase) - p4160_w.set_value(p4160_width) - p4415_m.set_value(p4415_mass) - p4415_s.set_value(p4415_scale) - p4415_p.set_value(p4415_phase) - p4415_w.set_value(p4415_width) - rho_m.set_value(rho_mass) - rho_s.set_value(rho_scale) - rho_p.set_value(rho_phase) - rho_w.set_value(rho_width) - omega_m.set_value(omega_mass) - omega_s.set_value(omega_scale) - omega_p.set_value(omega_phase) - omega_w.set_value(omega_width) - phi_m.set_value(phi_mass) - phi_s.set_value(phi_scale) - phi_p.set_value(phi_phase) - phi_w.set_value(phi_width) - Dstar_m.set_value(Dstar_mass) - DDstar_s.set_value(0.0) - DDstar_p.set_value(0.0) - D_m.set_value(D_mass) - Dbar_m.set_value(Dbar_mass) - Dbar_s.set_value(0.0) - Dbar_p.set_value(0.0) - tau_m.set_value(pdg['tau_M']) - Ctt.set_value(0.0) - b0_0.set_value(0.292) - b0_1.set_value(0.281) - b0_2.set_value(0.150) - bplus_0.set_value(0.466) - bplus_1.set_value(-0.885) - bplus_2.set_value(-0.213) - bT_0.set_value(0.460) - bT_1.set_value(-1.089) - bT_2.set_value(-1.114) - - -# # Analysis - -# In[39]: - - -# # zfit.run.numeric_checks = False - -# fitting_range = 'cut' -# 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 -# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR - -# Ctt_list = [] -# Ctt_error_list = [] - -# nr_of_toys = 1 -# if fitting_range == 'cut': -# nevents = int(pdg["number_of_decays"]*cut_BR) -# else: -# nevents = int(pdg["number_of_decays"]) -# # nevents = pdg["number_of_decays"] -# event_stack = 1000000 -# # nevents *= 41 -# # zfit.settings.set_verbosity(10) -# calls = int(nevents/event_stack + 1) - -# total_samp = [] - -# start = time.time() - -# sampler = total_f.create_sampler(n=event_stack) - -# for toy in range(nr_of_toys): - -# ### Generate data - -# # clear_output(wait=True) - -# print("Toy {}: Generating data...".format(toy)) - -# dirName = 'data/zfit_toys/toy_{0}'.format(toy) - -# if not os.path.exists(dirName): -# os.mkdir(dirName) -# print("Directory " , dirName , " Created ") - -# reset_param_values() - -# if fitting_range == 'cut': - -# sampler.resample(n=nevents) -# s = sampler.unstack_x() -# sam = zfit.run(s) -# calls = 0 -# c = 1 - -# else: -# for call in range(calls): - -# sampler.resample(n=event_stack) -# s = sampler.unstack_x() -# sam = zfit.run(s) - -# c = call + 1 - -# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: -# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) - -# print("Toy {}: Data generation finished".format(toy)) - -# ### Load data - -# print("Toy {}: Loading data...".format(toy)) - -# if fitting_range == 'cut': - -# total_samp = sam - -# else: - -# for call in range(calls): -# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: -# sam = pkl.load(input_file) -# total_samp = np.append(total_samp, sam) - -# total_samp = total_samp.astype('float64') - -# if fitting_range == 'full': - -# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) - -# print("Toy {}: Loading data finished".format(toy)) - -# ### Fit data - -# print("Toy {}: Fitting pdf...".format(toy)) - -# for param in total_f.get_dependents(): -# param.randomize() - -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# print("Toy {}: Fitting finished".format(toy)) - -# print("Function minimum:", result.fmin) -# print("Hesse errors:", result.hesse()) - -# params = result.params -# Ctt_list.append(params[Ctt]['value']) -# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) - -# #plotting the result - -# plotdirName = 'data/plots'.format(toy) - -# if not os.path.exists(plotdirName): -# os.mkdir(plotdirName) -# # print("Directory " , dirName , " Created ") - -# probs = total_f.pdf(test_q, norm_range=False) -# calcs_test = zfit.run(probs) -# plt.clf() -# plt.plot(test_q, calcs_test, label = 'pdf') -# plt.legend() -# plt.ylim(0.0, 6e-6) -# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) - -# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) - -# if fitting_range == 'cut': - -# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) - -# tot_sam_1 = total_samp[_1] - -# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) - -# tot_sam_2 = total_samp[_2] - -# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) - -# tot_sam_3 = total_samp[_3] - -# tot_sam = np.append(tot_sam_1, tot_sam_2) -# tot_sam = np.append(tot_sam, tot_sam_3) - -# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) - -# print("Toy {}: Loading data finished".format(toy)) - -# ### Fit data - -# print("Toy {}: Fitting pdf...".format(toy)) - -# for param in total_f_fit.get_dependents(): -# param.randomize() - -# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# print("Function minimum:", result.fmin) -# print("Hesse errors:", result.hesse()) - -# params = result.params - -# if result.converged: -# Ctt_list.append(params[Ctt]['value']) -# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) - -# #plotting the result - -# plotdirName = 'data/plots'.format(toy) - -# if not os.path.exists(plotdirName): -# os.mkdir(plotdirName) -# # print("Directory " , dirName , " Created ") - -# plt.clf() -# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') -# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) - - -# probs = total_f_fit.pdf(test_q, norm_range=False) -# calcs_test = zfit.run(probs) -# plt.clf() -# plt.plot(test_q, calcs_test, label = 'pdf') -# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.legend() -# plt.ylim(0.0, 1.5e-6) -# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) - -# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) - - - -# In[40]: - - -# with open("data/results/Ctt_list.pkl", "wb") as f: -# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) -# with open("data/results/Ctt_error_list.pkl", "wb") as f: -# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) - - -# In[41]: - - -# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) -# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) -# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) -# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) - - -# In[42]: - - -# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) - -# plt.show() - -# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) - -# tot_sam.shape - - -# In[43]: - - -# Ctt.floating = False - - -# In[44]: - - -# zfit.run(nll.value()) - - -# In[45]: - - -# result.fmin - - -# In[46]: - - -# BR_steps = np.linspace(0.0, 1e-3, 11) - - -# # CLS Code - -# In[47]: - - -# zfit.run.numeric_checks = False - -load = False - -bo5 = True - -bo5_set = 5 - -fitting_range = 'cut' -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 -cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR - -Ctt_list = [] -Ctt_error_list = [] - -nr_of_toys = 1 -nevents = int(pdg["number_of_decays"]*cut_BR) -# nevents = pdg["number_of_decays"] -event_stack = 1000000 -# nevents *= 41 -# zfit.settings.set_verbosity(10) - -mi = 0.0 -ma = 1e-3 -ste = 11 - -BR_steps = np.linspace(mi, ma, ste) - -Ctt_steps = np.sqrt(BR_steps/4.2*1000) - -total_samp = [] - -start = time.time() - -Nll_list = [] - -sampler = total_f.create_sampler(n=nevents) - -__ = 0 - - -#----------------------------------------------------- - -if not load: - - for Ctt_step in Ctt_steps: - - __ += 1 - - newset = True - - for floaty in [True, False]: - - Ctt.floating = floaty - - Nll_list.append([]) - - if bo5: - - while len(Nll_list[-1])/bo5_set < nr_of_toys: - - print('Step: {0}/{1}'.format(__, ste)) - - print('Current Ctt: {0}'.format(Ctt_step)) - print('Ctt floating: {0}'.format(floaty)) - - print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) - - reset_param_values() - - if floaty: - Ctt.set_value(Ctt_step) - else: - Ctt.set_value(0.0) - - if newset: - sampler.resample(n=nevents) - s = sampler.unstack_x() - total_samp = zfit.run(s) - calls = 0 - c = 1 - newset = False - - - data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) - - ### Fit data - - for param in total_f_fit.get_dependents(): - param.randomize() - - nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - - minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) - # minimizer._use_tfgrad = False - result = minimizer.minimize(nll) - - # print("Function minimum:", result.fmin) - # print("Hesse errors:", result.hesse()) - - params = result.params - - if result.converged: - Nll_list[-1].append(result.fmin) - - else: - - while len(Nll_list[-1]) < nr_of_toys: - - print('Step: {0}/{1}'.format(__, ste)) - - print('Current Ctt: {0}'.format(Ctt_step)) - print('Ctt floating: {0}'.format(floaty)) - - print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) - - reset_param_values() - - if floaty: - Ctt.set_value(Ctt_step) - else: - Ctt.set_value(0.0) - - if floaty: - sampler.resample(n=nevents) - s = sampler.unstack_x() - total_samp = zfit.run(s) - calls = 0 - c = 1 - - - data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) - - ### Fit data - - for param in total_f_fit.get_dependents(): - param.randomize() - - nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - - minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) - # minimizer._use_tfgrad = False - result = minimizer.minimize(nll) - - # print("Function minimum:", result.fmin) - # print("Hesse errors:", result.hesse()) - - params = result.params - - if result.converged: - Nll_list[-1].append(result.fmin) - - _t = int(time.time()-start) - - print('Time Taken: {}'.format(display_time(int(_t)))) - - print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) - - -# In[48]: - - -if load: - Nll_list = [] - CLs_values = [] - - _dir = 'data/CLs/finished/f1d1' - - jobs = os.listdir(_dir) - - for s in range(ste): - CLs_values.append([]) - - for s in range(2*ste): - Nll_list.append([]) - - for job in jobs: - if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): - print(job) - continue - - with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: - _Nll_list = pkl.load(input_file) - - if bo5: - for s in range(2*ste): - Nll_list[s].append(np.min(_Nll_list[s])) - else: - for s in range(2*ste): - Nll_list[s].extend(_Nll_list[s]) - - with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: - _CLs_values = pkl.load(input_file) - - for s in range(ste): - CLs_values[s].extend(_CLs_values[s]) - - print(np.shape(Nll_list)) - - -# In[50]: - - -dirName = 'data/CLs' - -# if bo5 and not load: -# for s in range(2*ste): -# Nll_list[s] = [np.min(Nll_list[s])] - -if bo5: - CLs_values= [] - for i in range(int(len(Nll_list)/2)): - CLs_values.append([]) - for j in range(len(Nll_list[0])): - CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) - - -if not load: - - CLs_values = [] - - for i in range(int(len(Nll_list)/2)): - CLs_values.append([]) - for j in range(nr_of_toys): - CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) - - if not os.path.exists(dirName): - os.mkdir(dirName) - print("Directory " , dirName , " Created ") - - with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: - pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) - - with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: - pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) - - -# In[51]: - - -# print(CLs_values) -print(Nll_list) - - -# ## Plot - -# In[52]: - - -l = [] - -for i in range(len(CLs_values)): - plt.clf() - plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) - plt.hist(CLs_values[0], bins = 100, label = 'Ctt fixed to 0') - plt.hist(CLs_values[i], bins = 100, label = 'Ctt floating') - plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=0.7, linestyle = 'dotted') - plt.legend() - plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) - - l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) - - -# In[53]: - - -for s in range(len(l)): - print('BR: {}'.format(BR_steps[s])) - print(2*l[s]/len(CLs_values[0])) - print() - - -# In[54]: - - -# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) - - -# In[ ]: - - - - diff --git a/data/CLs/finished/f1d1/2254891/test.png b/data/CLs/finished/f1d1/2254891/test.png deleted file mode 100644 index 1455457..0000000 --- a/data/CLs/finished/f1d1/2254891/test.png +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254896/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/2254896/__pycache__/helperfunctions.cpython-37.pyc deleted file mode 100644 index 30cf970..0000000 --- a/data/CLs/finished/f1d1/2254896/__pycache__/helperfunctions.cpython-37.pyc +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254896/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/2254896/__pycache__/pdg_const.cpython-37.pyc deleted file mode 100644 index 4d627a4..0000000 --- a/data/CLs/finished/f1d1/2254896/__pycache__/pdg_const.cpython-37.pyc +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254896/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/2254896/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl deleted file mode 100644 index f1667f8..0000000 --- a/data/CLs/finished/f1d1/2254896/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254896/data/CLs/0.0-0.001_11s--CLs_list.pkl b/data/CLs/finished/f1d1/2254896/data/CLs/0.0-0.001_11s--CLs_list.pkl deleted file mode 100644 index f517f52..0000000 --- a/data/CLs/finished/f1d1/2254896/data/CLs/0.0-0.001_11s--CLs_list.pkl +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/2254896/helperfunctions.py b/data/CLs/finished/f1d1/2254896/helperfunctions.py deleted file mode 100644 index 88e120f..0000000 --- a/data/CLs/finished/f1d1/2254896/helperfunctions.py +++ /dev/null @@ -1,33 +0,0 @@ -# some helperfunctions - -import matplotlib -matplotlib.use("agg") -import matplotlib.pyplot as plt - -#Dislpay time (e.g. while generating points) - -display_intervals = ( - ('w', 604800), # 60 * 60 * 24 * 7 - ('d', 86400), # 60 * 60 * 24 - ('h', 3600), # 60 * 60 - ('min', 60), - ('s', 1), - ) - -def display_time(seconds, granularity=2): - result = [] - - for name, count in display_intervals: - value = seconds // count - if value: - seconds -= value * count - if value == 1: - name = name.rstrip('s') - result.append("{} {}".format(value, name)) - return ', '.join(result[:granularity]) - -def prepare_plot(title): - plt.title(title) - plt.grid() - plt.legend(loc = 'best') - plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/2254896/pdg_const.py b/data/CLs/finished/f1d1/2254896/pdg_const.py deleted file mode 100644 index 6645dd7..0000000 --- a/data/CLs/finished/f1d1/2254896/pdg_const.py +++ /dev/null @@ -1,226 +0,0 @@ -pdg = { - - - ###Particle masses### - - "mbstar" : 5415.4, - "mbstar0" : 5711.0, - "B0_M" : 5279.5, - "Bs_M" : 5366.7, - "Bplus_M" : 5279.3, - "Lb_M" : 5619.4, - "D0_M" : 1864.8, - "Dst_M" : 2010, - "pi_M" : 139.6, - "Jpsi_M" : 3096.9, - "Psi2s_M" : 3685.6, - "kaon_M" : 493.7, - "Ks_M" : 497.6, - "phi_M" : 1019.5, - "rho_M" : 775.26, - "rho_width" : 149.1, - "omega_M" : 782.65, - "omega_width" : 8.49, - - "muon_M" : 105.7, - "tau_M": 1776.86, - - "squark_M" : 95.0, - "bquark_M" : 4180.0, - "cquark_M" : 1275.0, - - "Bplus_tau" : 1.638e-12, - - ###Wilson coefficients### - - "C1" : -0.257, - "C2" : 1.009, - "C3" : -0.005, - "C4" : -0.078, - - "C7eff" : -0.306, - "C9eff" : 4.211, - "C10eff" : -4.103, - -# "C7eff": 0.0, -# "C9eff": 0.0, -# "C10eff": 0.0, - - ###Other constants - - "GF" : 1.1663787e-5, - "alpha_ew" : 1.0/137.0, - "Vts" : 0.0394, - "Vtb" : 1.019, - "number_of_decays": 5404696, - - #Formfactor z coefficients - - #"b0" : [0.285, 0.19, -0.17], - #"bplus" : [0.437, -1.41, -2.5], - #"bT" : [0.440, -1.47, -2.7] - - "b0" : [0.292, 0.281, 0.150], - "bplus" : [0.466, -0.885, -0.213], - "bT" : [0.460, -1.089, -1.114], - - "NR_BR": 4.37e-7, - "NR_auc": 0.00133, - - #Resonances format(mass, width, phase, scale) - - # pre scaling - -# "rho": (775.26, 149.0, -0.35, 1.0), - -# "omega": (782.7, 8.5, 0.26, 1.0), - -# "phi": (1019.46, 4.25, 0.5, 1.0), - -# "jpsi": (3096.0, 0.09, -1.5, 2e-2), -# "jpsi_auc": 0.2126825758464027, - -# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), -# "psi2s_auc": 2.802257483178487e-10, - -# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), - -# "p4040": (4039.0, 80.0, -2.52, 2.0), - -# "p4160": (4191.0, 70.0, -1.9, 2.2), - -# "p4415": (4421.0, 62.0, -2.52, 1.0), - - - # after scaling (Phase combination --) - - -# "rho": (743.2, 149.0, -0.22, 1.05), - -# "omega": (782.7, 8.5, 0.38, 6.8), - -# "phi": (1013.5, 4.25, 0.62, 19.2), - -# "jpsi": (3096.1, 0.09, 1.63, 9897.0), -# "jpsi_auc": 0.2126825758464027, -# "jpsi_phase_unc": 0.05, - -# "psi2s": (3686.0, 0.3, 1.8, 1396.0), -# "psi2s_auc": 0.0151332263, -# "psi2s_phase_unc": 0.1, - -# "p3770": (3773.0, 27.2, -2.95, 2.5), - -# "p4040": (4039.0, 80.0, -2.75, 1.01), - -# "p4160": (4191.0, 70.0, -2.28, 2.2), - -# "p4415": (4421.0, 62.0, -2.31, 1.24), - - # Phase combination of paper ++ - -# "rho": (743.2, 149.0, -0.35, 1.05), - -# "omega": (782.7, 8.5, 0.26, 6.8), - -# "phi": (1013.5, 4.25, 0.47, 19.2), - -# "jpsi": (3096.1, 0.09, -1.66, 9897.0), -# "jpsi_auc": 0.2126825758464027, -# "jpsi_phase_unc": 0.05, - -# "psi2s": (3686.0, 0.3, -1.93, 1396.0), -# "psi2s_auc": 0.0151332263, -# "psi2s_phase_unc": 0.1, - -# "p3770": (3773.0, 27.2, -2.13, 2.5), - -# "p4040": (4039.0, 80.0, -2.52, 1.01), - -# "p4160": (4191.0, 70.0, -1.90, 2.2), - -# "p4415": (4421.0, 62.0, -2.52, 1.24), - - # Phase combination of paper +- - - # "rho": (743.2, 149.0, -0.26, 1.05), - # - # "omega": (782.7, 8.5, 0.35, 6.8), - # - # "phi": (1013.5, 4.25, 0.58, 19.2), - # - # "jpsi": (3096.1, 0.09, 1.47, 9897.0), - # "jpsi_auc": 0.2126825758464027, - # "jpsi_phase_unc": 0.05, - # - # "psi2s": (3686.0, 0.3, -2.21, 1396.0), - # "psi2s_auc": 0.0151332263, - # "psi2s_phase_unc": 0.1, - # - # "p3770": (3773.0, 27.2, -2.140, 2.5), - # - # "p4040": (4039.0, 80.0, -2.64, 1.01), - # - # "p4160": (4191.0, 70.0, -2.11, 2.2), - # - # "p4415": (4421.0, 62.0, -2.42, 1.24), - - # Phase combination of paper -+ - - "rho": (743.2, 149.0, -0.30, 1.05), - - "omega": (782.7, 8.5, 0.30, 6.8), - - "phi": (1013.5, 4.25, 0.51, 19.2), - - "jpsi": (3096.1, 0.09, -1.5, 9897.0), - "jpsi_auc": 0.2126825758464027, - "jpsi_phase_unc": 0.05, - - "psi2s": (3686.0, 0.3, 2.08, 1396.0), - "psi2s_auc": 0.0151332263, - "psi2s_phase_unc": 0.1, - - "p3770": (3773.0, 27.2, -2.89, 2.5), - - "p4040": (4039.0, 80.0, -2.69, 1.01), - - "p4160": (4191.0, 70.0, -2.13, 2.2), - - "p4415": (4421.0, 62.0, -2.43, 1.24), - - - # zeroing resonances - -# "rho": (775.26, 149.0, -0.35, 0.0), -# "omega": (782.7, 8.5, 0.26, 0.0), -# "phi": (1019.46, 4.25, 0.5, 0.0), -# "jpsi": (3096.0, 0.09, -1.5, 0.0), -# "psi2s": (3686.0, 0.3, -1.5, 0.0), -# "p3770": (3773.0, 27.2, -2.13, 0.0), -# "p4040": (4039.0, 80.0, -2.52, 0.0), -# "p4160": (4147.0, 22.0, -1.9, 0.0), -# "p4415": (4421.0, 62.0, -2.52, 0.0), - - # 2P contributions format(mass, amp, phase) - -# "D_bar": ( - - #general - - "rho_BR": 1.7e-10, - "omega_BR": 4.9e-10, - "phi_BR": 2.5e-9, - "jpsi_BR": 6.02e-5, - "psi2s_BR": 4.97e-6, - "p3770_BR": 1.38e-9, - "p4040_BR": 4.2e-10, - "p4160_BR": 2.6e-9, - "p4415_BR": 6.1e-10, - -# Estimates - "Dbar_scale": 1.46, #with phase = pi - - "DDstar_scale": 2.41, #with phase = pi - - } diff --git a/data/CLs/finished/f1d1/2254896/raremodel-nb1.py b/data/CLs/finished/f1d1/2254896/raremodel-nb1.py deleted file mode 100644 index 1a5d9be..0000000 --- a/data/CLs/finished/f1d1/2254896/raremodel-nb1.py +++ /dev/null @@ -1,1939 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -# # Import - -# In[1]: - - -import os - -# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" - -import numpy as np -from pdg_const import pdg -import matplotlib -import matplotlib.pyplot as plt -import pickle as pkl -import sys -import time -from helperfunctions import display_time, prepare_plot -import cmath as c -import scipy.integrate as integrate -from scipy.optimize import fminbound -from array import array as arr -import collections -from itertools import compress -import tensorflow as tf -import zfit -from zfit import ztf -# from IPython.display import clear_output -import os -import tensorflow_probability as tfp -tfd = tfp.distributions - - -# In[2]: - - -# chunksize = 10000 -# zfit.run.chunking.active = True -# zfit.run.chunking.max_n_points = chunksize - - -# # Build model and graphs -# ## Create graphs - -# In[ ]: - - - - - -# In[3]: - - -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 - #check if subscript is viable - - if subscript != "0" and subscript != "+" and subscript != "T": - raise ValueError('Wrong subscript entered, choose either 0, + or T') - - #get constants - - mK = ztf.constant(pdg['Ks_M']) - mbstar0 = ztf.constant(pdg["mbstar0"]) - mbstar = ztf.constant(pdg["mbstar"]) - - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mB = ztf.constant(pdg['Bplus_M']) - - #N comes from derivation in paper - - N = 3 - - #some helperfunctions - - tpos = (mB - mK)**2 - tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 - - z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) - z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) - z = tf.divide(z_oben, z_unten) - - #calculate f0 - - if subscript == "0": - prefactor = 1/(1 - q2/(mbstar0**2)) - _sum = 0 - b0 = [b0_0, b0_1, b0_2] - - for i in range(N): - _sum += b0[i]*(tf.pow(z,i)) - - return ztf.to_complex(prefactor * _sum) - - #calculate f+ or fT - - else: - prefactor = 1/(1 - q2/(mbstar**2)) - _sum = 0 - - if subscript == "T": - bT = [bT_0, bT_1, bT_2] - for i in range(N): - _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) - else: - bplus = [bplus_0, bplus_1, bplus_2] - for i in range(N): - _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) - - return ztf.to_complex(prefactor * _sum) - -def resonance(q, _mass, width, phase, scale): - - q2 = tf.pow(q, 2) - - mmu = ztf.constant(pdg['muon_M']) - - p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) - - p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) - - gamma_j = tf.divide(p, q) * _mass * width / p0 - - #Calculate the resonance - - _top = tf.complex(_mass * width, ztf.constant(0.0)) - - _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) - - com = _top/_bottom - - #Rotate by the phase - - r = ztf.to_complex(scale*tf.abs(com)) - - _phase = tf.angle(com) - - _phase += phase - - com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) - - return com - - -def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): - - GF = ztf.constant(pdg['GF']) - alpha_ew = ztf.constant(pdg['alpha_ew']) - Vtb = ztf.constant(pdg['Vtb']) - Vts = ztf.constant(pdg['Vts']) - C10eff = ztf.constant(pdg['C10eff']) - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mK = ztf.constant(pdg['Ks_M']) - mB = ztf.constant(pdg['Bplus_M']) - - q2 = tf.pow(q, 2) - - #Some helperfunctions - - beta = 1. - 4. * mmu**2. / q2 - - 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.) - - #prefactor in front of whole bracket - - prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) - - #left term in bracket - - 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) - - #middle term in bracket - - _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) - - _under = q2 * mB**2. - - 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) - - #Note sqrt(q2) comes from derivation as we use q2 and plot q - - return prefactor1 * (bracket_left + bracket_middle) * 2 * q - -def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): - - q2 = tf.pow(q, 2) - - GF = ztf.constant(pdg['GF']) - alpha_ew = ztf.constant(pdg['alpha_ew']) - Vtb = ztf.constant(pdg['Vtb']) - Vts = ztf.constant(pdg['Vts']) - C7eff = ztf.constant(pdg['C7eff']) - - mmu = ztf.constant(pdg['muon_M']) - mb = ztf.constant(pdg['bquark_M']) - ms = ztf.constant(pdg['squark_M']) - mK = ztf.constant(pdg['Ks_M']) - mB = ztf.constant(pdg['Bplus_M']) - - #Some helperfunctions - - beta = 1. - 4. * mmu**2. / q2 - - 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) - - #prefactor in front of whole bracket - - prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) - - #right term in bracket - - prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) - - 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) - - bracket_right = prefactor2 * abs_bracket - - #Note sqrt(q2) comes from derivation as we use q2 and plot q - - return prefactor1 * bracket_right * 2 * q - -def c9eff(q, funcs): - - C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) - - c9 = C9eff_nr + funcs - - return c9 - - -# In[4]: - - -def G(y): - - def inner_rect_bracket(q): - return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) - - def inner_right(q): - return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) - - big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) - - return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket - -def h_S(m, q): - - 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))) - -def h_P(m, q): - - 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) - -def two_p_ccbar(mD, m_D_bar, m_D_star, q): - - - #Load constants - nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) - nu_D = ztf.to_complex(pdg["nu_D"]) - nu_D_star = ztf.to_complex(pdg["nu_D_star"]) - - phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) - phase_D = ztf.to_complex(pdg["phase_D"]) - phase_D_star = ztf.to_complex(pdg["phase_D_star"]) - - #Calculation - left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) - - right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) - - right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) - - return left_part + right_part_D + right_part_D_star - - -# ## Build pdf - -# In[5]: - - -class total_pdf_cut(zfit.pdf.ZPDF): - _N_OBS = 1 # dimension, can be omitted - _PARAMS = ['b0_0', 'b0_1', 'b0_2', - 'bplus_0', 'bplus_1', 'bplus_2', - 'bT_0', 'bT_1', 'bT_2', - 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', - 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', - 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', - 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', - 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', - 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', - 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', - 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', - 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', - 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', - 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', - 'tau_mass', 'C_tt'] -# the name of the parameters - - def _unnormalized_pdf(self, x): - - x = x.unstack_x() - - b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] - bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] - bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] - - def rho_res(q): - return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], - phase = self.params['rho_phase'], width = self.params['rho_width']) - - def omega_res(q): - return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], - phase = self.params['omega_phase'], width = self.params['omega_width']) - - def phi_res(q): - return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], - phase = self.params['phi_phase'], width = self.params['phi_width']) - - def jpsi_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], - scale = self.params['jpsi_scale'], - phase = self.params['jpsi_phase'], - width = self.params['jpsi_width']) - def psi2s_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], - scale = self.params['psi2s_scale'], - phase = self.params['psi2s_phase'], - width = self.params['psi2s_width']) - def p3770_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], - scale = self.params['p3770_scale'], - phase = self.params['p3770_phase'], - width = self.params['p3770_width']) - - def p4040_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], - scale = self.params['p4040_scale'], - phase = self.params['p4040_phase'], - width = self.params['p4040_width']) - - def p4160_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], - scale = self.params['p4160_scale'], - phase = self.params['p4160_phase'], - width = self.params['p4160_width']) - - def p4415_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], - scale = self.params['p4415_scale'], - phase = self.params['p4415_phase'], - width = self.params['p4415_width']) - - def P2_D(q): - 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)) - 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))) - return Dbar_contrib + DDstar_contrib - - def ttau_cusp(q): - 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))) - - - 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) - - vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - tot = vec_f + axiv_nr - - #Cut out jpsi and psi2s - - tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) - - tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) - - return tot - -class total_pdf_full(zfit.pdf.ZPDF): - _N_OBS = 1 # dimension, can be omitted - _PARAMS = ['b0_0', 'b0_1', 'b0_2', - 'bplus_0', 'bplus_1', 'bplus_2', - 'bT_0', 'bT_1', 'bT_2', - 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', - 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', - 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', - 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', - 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', - 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', - 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', - 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', - 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', - 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', - 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', - 'tau_mass', 'C_tt'] -# the name of the parameters - - def _unnormalized_pdf(self, x): - - x = x.unstack_x() - - b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] - bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] - bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] - - def rho_res(q): - return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], - phase = self.params['rho_phase'], width = self.params['rho_width']) - - def omega_res(q): - return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], - phase = self.params['omega_phase'], width = self.params['omega_width']) - - def phi_res(q): - return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], - phase = self.params['phi_phase'], width = self.params['phi_width']) - - def jpsi_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], - scale = self.params['jpsi_scale'], - phase = self.params['jpsi_phase'], - width = self.params['jpsi_width']) - def psi2s_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], - scale = self.params['psi2s_scale'], - phase = self.params['psi2s_phase'], - width = self.params['psi2s_width']) - def p3770_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], - scale = self.params['p3770_scale'], - phase = self.params['p3770_phase'], - width = self.params['p3770_width']) - - def p4040_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], - scale = self.params['p4040_scale'], - phase = self.params['p4040_phase'], - width = self.params['p4040_width']) - - def p4160_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], - scale = self.params['p4160_scale'], - phase = self.params['p4160_phase'], - width = self.params['p4160_width']) - - def p4415_res(q): - return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], - scale = self.params['p4415_scale'], - phase = self.params['p4415_phase'], - width = self.params['p4415_width']) - - def P2_D(q): - 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)) - 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))) - return Dbar_contrib + DDstar_contrib - - def ttau_cusp(q): - 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))) - - - 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) - - vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) - - tot = vec_f + axiv_nr - - #Cut out jpsi and psi2s - -# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) - -# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) - - return tot - - -# ## Setup parameters - -# In[6]: - - -# formfactors - -b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) - -bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) -bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) -bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) - -bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) -bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) - - -#rho - -rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] - -rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) -rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) -rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#omega - -omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] - -omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) -omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) -omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - - -#phi - -phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] - -phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) -phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) -phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#jpsi - -jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] - -jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) -jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) -jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi2s - -psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] - -psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) -psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) -psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(3770) - -p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] - -p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) -p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) -p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4040) - -p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] - -p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) -p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) -p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4160) - -p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] - -p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) -p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) -p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - -#psi(4415) - -p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] - -p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) -p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) -p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) -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)) - - -# ## Dynamic generation of 2 particle contribution - -# In[7]: - - -m_c = 1300 - -Dbar_phase = 0.0 -DDstar_phase = 0.0 -Dstar_mass = pdg['Dst_M'] -Dbar_mass = pdg['D0_M'] -D_mass = pdg['D0_M'] - -Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) -Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) -Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) -DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) -Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) -D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) -DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) - - -# ## Tau parameters - -# In[8]: - - -tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) -Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) - - -# ## Load data - -# In[9]: - - -x_min = 2*pdg['muon_M'] -x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) - -# # Full spectrum - -obs_toy = zfit.Space('q', limits = (x_min, x_max)) - -# Jpsi and Psi2s cut out - -obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) -obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) -obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) - -obs_fit = obs1 + obs2 + obs3 - -# 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: -# part_set = pkl.load(input_file) - -# x_part = part_set['x_part'] - -# x_part = x_part.astype('float64') - -# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) - - -# ## Setup pdf - -# In[10]: - - -total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, - psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, - p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, - p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, - p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, - p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, - rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, - omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, - phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, - Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, - Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, - tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, - bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, - bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) - -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, - psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, - p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, - p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, - p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, - p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, - rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, - omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, - phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, - Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, - Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, - tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, - bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, - bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) - -# print(total_pdf.obs) - -# print(calcs_test) - -# for param in total_f.get_dependents(): -# print(zfit.run(param)) - - -# In[11]: - - -total_f_fit.normalization(obs_toy) - - -# ## Test if graphs actually work and compute values - -# In[12]: - - -# def total_test_tf(xq): - -# def jpsi_res(q): -# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) - -# def psi2s_res(q): -# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) - -# def cusp(q): -# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) - -# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) - -# vec_f = vec(xq, funcs) - -# axiv_nr = axiv_nonres(xq) - -# tot = vec_f + axiv_nr - -# return tot - -# def jpsi_res(q): -# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) - -# calcs = zfit.run(total_test_tf(x_part)) - -test_q = np.linspace(x_min, x_max, int(2e6)) - -probs = total_f_fit.pdf(test_q, norm_range=False) - -calcs_test = zfit.run(probs) -# res_y = zfit.run(jpsi_res(test_q)) -# b0 = [b0_0, b0_1, b0_2] -# bplus = [bplus_0, bplus_1, bplus_2] -# bT = [bT_0, bT_1, bT_2] -# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) -# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) -# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) - - -# In[13]: - - -plt.clf() -# plt.plot(x_part, calcs, '.') -plt.plot(test_q, calcs_test, label = 'pdf') -# plt.plot(test_q, f0_y, label = '0') -# plt.plot(test_q, fT_y, label = 'T') -# plt.plot(test_q, fplus_y, label = '+') -# plt.plot(test_q, res_y, label = 'res') -plt.legend() -plt.ylim(0.0, 1.5e-6) -# plt.yscale('log') -# plt.xlim(770, 785) -plt.savefig('test.png') -# print(jpsi_width) - - -# In[14]: - - - - -# probs = mixture.prob(test_q) -# probs_np = zfit.run(probs) -# probs_np *= np.max(calcs_test) / np.max(probs_np) -# plt.figure() -# plt.semilogy(test_q, probs_np,label="importance sampling") -# plt.semilogy(test_q, calcs_test, label = 'pdf') - - -# In[15]: - - -# 0.213/(0.00133+0.213+0.015) - - -# ## Adjust scaling of different parts - -# In[16]: - - -total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) -# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) -# inte_fl = zfit.run(inte) -# print(inte_fl/4500) -# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) - - -# In[17]: - - -# # print("jpsi:", inte_fl) -# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - -# # print("psi2s:", inte_fl) -# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - -# name = "phi" - -# print(name+":", inte_fl) -# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) -# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) - - -# print(x_min) -# print(x_max) -# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) -# total_f.update_integration_options(mc_sampler=lambda dim, num_results, -# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), -# draws_per_dim=1000000) -# # _ = [] - -# # for i in range(10): - -# # inte = total_f.integrate(limits = (x_min, x_max)) -# # inte_fl = zfit.run(inte) -# # print(inte_fl) -# # _.append(inte_fl) - -# # print("mean:", np.mean(_)) - -# _ = time.time() - -# inte = total_f.integrate(limits = (x_min, x_max)) -# inte_fl = zfit.run(inte) -# print(inte_fl) -# print("Time taken: {}".format(display_time(int(time.time() - _)))) - -# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) -# print(0.25**2*4.2/1000) - - -# # Sampling -# ## Mixture distribution for sampling - -# In[18]: - - - - -# print(list_of_borders[:9]) -# print(list_of_borders[-9:]) - - -class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): - def __call__(self, limits, dtype, n_to_produce): - # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) - low, high = limits.limit1d - low = tf.cast(low, dtype=dtype) - high = tf.cast(high, dtype=dtype) -# uniform = tfd.Uniform(low=low, high=high) -# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) -# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) - -# list_of_borders = [] -# _p = [] -# splits = 10 - -# _ = np.linspace(x_min, x_max, splits) - -# for i in range(splits): -# list_of_borders.append(tf.constant(_[i], dtype=dtype)) -# _p.append(tf.constant(1/splits, dtype=dtype)) - -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), -# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], -# high=list_of_borders[-(splits-1):])) - mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), - tf.constant(0.93, dtype=dtype), - tf.constant(0.05, dtype=dtype), - tf.constant(0.065, dtype=dtype), - tf.constant(0.04, dtype=dtype), - tf.constant(0.05, dtype=dtype)]), - components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), - tf.constant(3090, dtype=dtype), - tf.constant(3681, dtype=dtype), - tf.constant(3070, dtype=dtype), - tf.constant(1000, dtype=dtype), - tf.constant(3660, dtype=dtype)], - high=[tf.constant(x_max, dtype=dtype), - tf.constant(3102, dtype=dtype), - tf.constant(3691, dtype=dtype), - tf.constant(3110, dtype=dtype), - tf.constant(1040, dtype=dtype), - tf.constant(3710, dtype=dtype)])) -# dtype = tf.float64 -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), -# tf.constant(0.90, dtype=dtype), -# tf.constant(0.02, dtype=dtype), -# tf.constant(0.07, dtype=dtype), -# tf.constant(0.02, dtype=dtype)]), -# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), -# tf.constant(3089, dtype=dtype), -# tf.constant(3103, dtype=dtype), -# tf.constant(3681, dtype=dtype), -# tf.constant(3691, dtype=dtype)], -# high=[tf.constant(3089, dtype=dtype), -# tf.constant(3103, dtype=dtype), -# tf.constant(3681, dtype=dtype), -# tf.constant(3691, dtype=dtype), -# tf.constant(x_max, dtype=dtype)])) -# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) -# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) - sample = mixture.sample((n_to_produce, 1)) -# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) - weights = mixture.prob(sample)[:,0] -# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) - # sample = tf.expand_dims(sample, axis=-1) -# print(sample, weights) - -# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) - weights_max = None - thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) - return sample, thresholds, weights, weights_max, n_to_produce - - -# In[19]: - - -# total_f._sample_and_weights = UniformSampleAndWeights - - -# In[20]: - - -# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) - - -# In[21]: - - -# zfit.settings.set_verbosity(10) - - -# In[22]: - - -# # zfit.run.numeric_checks = False - -# nr_of_toys = 1 -# nevents = int(pdg["number_of_decays"]) -# nevents = pdg["number_of_decays"] -# event_stack = 1000000 -# # zfit.settings.set_verbosity(10) -# calls = int(nevents/event_stack + 1) - -# total_samp = [] - -# start = time.time() - -# sampler = total_f.create_sampler(n=event_stack) - -# for toy in range(nr_of_toys): - -# dirName = 'data/zfit_toys/toy_{0}'.format(toy) - -# if not os.path.exists(dirName): -# os.mkdir(dirName) -# print("Directory " , dirName , " Created ") - -# for call in range(calls): - -# sampler.resample(n=event_stack) -# s = sampler.unstack_x() -# sam = zfit.run(s) -# # clear_output(wait=True) - -# c = call + 1 - -# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) - -# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: -# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) - - -# In[23]: - - -# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: -# sam = pkl.load(input_file) -# print(sam[:10]) - -# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: -# sam2 = pkl.load(input_file) -# print(sam2[:10]) - -# print(np.sum(sam-sam2)) - - -# In[24]: - - -# print("Time to generate full toy: {} s".format(int(time.time()-start))) - -# total_samp = [] - -# for call in range(calls): -# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: -# sam = pkl.load(input_file) -# total_samp = np.append(total_samp, sam) - -# total_samp = total_samp.astype('float64') - -# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) - -# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) - -# print(total_samp[:nevents].shape) - - -# In[25]: - - -# plt.clf() - -# bins = int((x_max-x_min)/7) - -# # calcs = zfit.run(total_test_tf(samp)) -# print(total_samp[:nevents].shape) - -# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') -# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') - -# # plt.plot(sam, calcs, '.') -# # plt.plot(test_q, calcs_test) -# # plt.yscale('log') -# plt.ylim(0, 200) -# # plt.xlim(3080, 3110) - -# plt.legend() - -# plt.savefig('test2.png') - - -# In[26]: - - -# sampler = total_f.create_sampler(n=nevents) -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) - -# # for param in pdf.get_dependents(): -# # param.set_value(initial_value) - -# sampler.resample(n=nevents) - -# # Randomise initial values -# # for param in pdf.get_dependents(): -# # param.set_value(random value here) - -# # Minimise the NLL -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) -# minimum = minimizer.minimize(nll) - - -# In[27]: - - -# jpsi_width - - -# In[28]: - - -# plt.hist(sample, weights=1 / prob(sample)) - - -# # Fitting - -# In[29]: - - -# start = time.time() - -# for param in total_f.get_dependents(): -# param.randomize() - -# # for param in total_f.get_dependents(): -# # print(zfit.run(param)) - -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# # param_errors = result.error() - -# # for var, errors in param_errors.items(): -# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) - -# print("Function minimum:", result.fmin) -# # print("Results:", result.params) -# print("Hesse errors:", result.hesse()) - - -# In[30]: - - -# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) - -# # probs = total_f.pdf(test_q) - -# calcs_test = zfit.run(probs) -# res_y = zfit.run(jpsi_res(test_q)) - - -# In[31]: - - -# plt.clf() -# # plt.plot(x_part, calcs, '.') -# plt.plot(test_q, calcs_test, label = 'pdf') -# # plt.plot(test_q, res_y, label = 'res') -# plt.legend() -# plt.ylim(0.0, 10e-6) -# # plt.yscale('log') -# # plt.xlim(3080, 3110) -# plt.savefig('test3.png') -# # print(jpsi_width) - - -# In[32]: - - -# _tot = 4.37e-7+6.02e-5+4.97e-6 -# _probs = [] -# _probs.append(6.02e-5/_tot) -# _probs.append(4.97e-6/_tot) -# _probs.append(4.37e-7/_tot) -# print(_probs) - - -# In[33]: - - -# dtype = 'float64' -# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) -# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), -# tf.constant(0.917, dtype=dtype), -# tf.constant(0.076, dtype=dtype)]), -# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), -# tf.constant(3080, dtype=dtype), -# tf.constant(3670, dtype=dtype)], -# high=[tf.constant(x_max, dtype=dtype), -# tf.constant(3112, dtype=dtype), -# tf.constant(3702, dtype=dtype)])) -# # for i in range(10): -# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) - - -# In[34]: - - -# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) -# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) - - -# In[35]: - - -# def jpsi_res(q): -# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, -# phase = jpsi_phase, width = jpsi_width) - -# def psi2s_res(q): -# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, -# phase = psi2s_phase, width = psi2s_width) - -# def p3770_res(q): -# return resonance(q, _mass = p3770_mass, scale = p3770_scale, -# phase = p3770_phase, width = p3770_width) - -# def p4040_res(q): -# return resonance(q, _mass = p4040_mass, scale = p4040_scale, -# phase = p4040_phase, width = p4040_width) - -# def p4160_res(q): -# return resonance(q, _mass = p4160_mass, scale = p4160_scale, -# phase = p4160_phase, width = p4160_width) - -# def p4415_res(q): -# return resonance(q, _mass = p4415_mass, scale = p4415_scale, -# phase = p4415_phase, width = p4415_width) - - -# In[36]: - - -# 0.15**2*4.2/1000 -# result.hesse() - - -# ## Constraints - -# In[37]: - - -# 1. Constraint - Real part of sum of Psi contrib and D contribs - -sum_list = [] - -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)))) -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)))) -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)))) -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)))) -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)))) -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)))) -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))))) -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)))) - -sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) - -for part in sum_list: - sum_ru_1 += part - -sum_1 = tf.math.real(sum_ru_1) -# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), -# sigma = ztf.constant(2.2*10**-8)) - -constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) - -# 2. Constraint - Abs. of sum of Psi contribs and D contribs - -sum_2 = tf.abs(sum_ru_1) -constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) - -# 3. Constraint - Maximum eta of D contribs - -constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) - -constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) - -# 4. Constraint - Formfactor multivariant gaussian covariance fplus - -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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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)], - [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.)]] - -def triGauss(val1,val2,val3,m = Cov_matrix): - - mean1 = ztf.constant(0.466) - mean2 = ztf.constant(-0.885) - mean3 = ztf.constant(-0.213) - sigma1 = ztf.constant(0.014) - sigma2 = ztf.constant(0.128) - sigma3 = ztf.constant(0.548) - x1 = (val1-mean1)/sigma1 - x2 = (val2-mean2)/sigma2 - x3 = (val3-mean3)/sigma3 - rho12 = m[0][1] - rho13 = m[0][2] - rho23 = m[1][2] - 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)) - d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) - - fcn = -w/d - chisq = -2*fcn - return chisq - -constraint4 = triGauss(bplus_0, bplus_1, bplus_2) - -# mean1 = ztf.constant(0.466) -# mean2 = ztf.constant(-0.885) -# mean3 = ztf.constant(-0.213) -# sigma1 = ztf.constant(0.014) -# sigma2 = ztf.constant(0.128) -# sigma3 = ztf.constant(0.548) -# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) -# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) -# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) - -# 5. Constraint - Abs. of sum of light contribs - -sum_list_5 = [] - -sum_list_5.append(rho_s*rho_w/rho_m) -sum_list_5.append(omega_s*omega_w/omega_m) -sum_list_5.append(phi_s*phi_w/phi_m) - - -sum_ru_5 = ztf.constant(0.0) - -for part in sum_list_5: - sum_ru_5 += part - -constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) - -# 6. Constraint on phases of Jpsi and Psi2s for cut out fit - - -# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), -# sigma = ztf.constant(jpsi_phase)) -# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), -# sigma = ztf.constant(psi2s_phase)) - -constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) -constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) - -# 7. Constraint on Ctt with higher limits - -constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) - -constraint7dtype = tf.float64 - -# zfit.run(constraint6_0) - -# ztf.convert_to_tensor(constraint6_0) - -#List of all constraints - -constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, - constraint6_0, constraint6_1]#, constraint7] - - -# ## Reset params - -# In[38]: - - -def reset_param_values(): - jpsi_m.set_value(jpsi_mass) - jpsi_s.set_value(jpsi_scale) - jpsi_p.set_value(jpsi_phase) - jpsi_w.set_value(jpsi_width) - psi2s_m.set_value(psi2s_mass) - psi2s_s.set_value(psi2s_scale) - psi2s_p.set_value(psi2s_phase) - psi2s_w.set_value(psi2s_width) - p3770_m.set_value(p3770_mass) - p3770_s.set_value(p3770_scale) - p3770_p.set_value(p3770_phase) - p3770_w.set_value(p3770_width) - p4040_m.set_value(p4040_mass) - p4040_s.set_value(p4040_scale) - p4040_p.set_value(p4040_phase) - p4040_w.set_value(p4040_width) - p4160_m.set_value(p4160_mass) - p4160_s.set_value(p4160_scale) - p4160_p.set_value(p4160_phase) - p4160_w.set_value(p4160_width) - p4415_m.set_value(p4415_mass) - p4415_s.set_value(p4415_scale) - p4415_p.set_value(p4415_phase) - p4415_w.set_value(p4415_width) - rho_m.set_value(rho_mass) - rho_s.set_value(rho_scale) - rho_p.set_value(rho_phase) - rho_w.set_value(rho_width) - omega_m.set_value(omega_mass) - omega_s.set_value(omega_scale) - omega_p.set_value(omega_phase) - omega_w.set_value(omega_width) - phi_m.set_value(phi_mass) - phi_s.set_value(phi_scale) - phi_p.set_value(phi_phase) - phi_w.set_value(phi_width) - Dstar_m.set_value(Dstar_mass) - DDstar_s.set_value(0.0) - DDstar_p.set_value(0.0) - D_m.set_value(D_mass) - Dbar_m.set_value(Dbar_mass) - Dbar_s.set_value(0.0) - Dbar_p.set_value(0.0) - tau_m.set_value(pdg['tau_M']) - Ctt.set_value(0.0) - b0_0.set_value(0.292) - b0_1.set_value(0.281) - b0_2.set_value(0.150) - bplus_0.set_value(0.466) - bplus_1.set_value(-0.885) - bplus_2.set_value(-0.213) - bT_0.set_value(0.460) - bT_1.set_value(-1.089) - bT_2.set_value(-1.114) - - -# # Analysis - -# In[39]: - - -# # zfit.run.numeric_checks = False - -# fitting_range = 'cut' -# 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 -# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR - -# Ctt_list = [] -# Ctt_error_list = [] - -# nr_of_toys = 1 -# if fitting_range == 'cut': -# nevents = int(pdg["number_of_decays"]*cut_BR) -# else: -# nevents = int(pdg["number_of_decays"]) -# # nevents = pdg["number_of_decays"] -# event_stack = 1000000 -# # nevents *= 41 -# # zfit.settings.set_verbosity(10) -# calls = int(nevents/event_stack + 1) - -# total_samp = [] - -# start = time.time() - -# sampler = total_f.create_sampler(n=event_stack) - -# for toy in range(nr_of_toys): - -# ### Generate data - -# # clear_output(wait=True) - -# print("Toy {}: Generating data...".format(toy)) - -# dirName = 'data/zfit_toys/toy_{0}'.format(toy) - -# if not os.path.exists(dirName): -# os.mkdir(dirName) -# print("Directory " , dirName , " Created ") - -# reset_param_values() - -# if fitting_range == 'cut': - -# sampler.resample(n=nevents) -# s = sampler.unstack_x() -# sam = zfit.run(s) -# calls = 0 -# c = 1 - -# else: -# for call in range(calls): - -# sampler.resample(n=event_stack) -# s = sampler.unstack_x() -# sam = zfit.run(s) - -# c = call + 1 - -# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: -# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) - -# print("Toy {}: Data generation finished".format(toy)) - -# ### Load data - -# print("Toy {}: Loading data...".format(toy)) - -# if fitting_range == 'cut': - -# total_samp = sam - -# else: - -# for call in range(calls): -# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: -# sam = pkl.load(input_file) -# total_samp = np.append(total_samp, sam) - -# total_samp = total_samp.astype('float64') - -# if fitting_range == 'full': - -# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) - -# print("Toy {}: Loading data finished".format(toy)) - -# ### Fit data - -# print("Toy {}: Fitting pdf...".format(toy)) - -# for param in total_f.get_dependents(): -# param.randomize() - -# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# print("Toy {}: Fitting finished".format(toy)) - -# print("Function minimum:", result.fmin) -# print("Hesse errors:", result.hesse()) - -# params = result.params -# Ctt_list.append(params[Ctt]['value']) -# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) - -# #plotting the result - -# plotdirName = 'data/plots'.format(toy) - -# if not os.path.exists(plotdirName): -# os.mkdir(plotdirName) -# # print("Directory " , dirName , " Created ") - -# probs = total_f.pdf(test_q, norm_range=False) -# calcs_test = zfit.run(probs) -# plt.clf() -# plt.plot(test_q, calcs_test, label = 'pdf') -# plt.legend() -# plt.ylim(0.0, 6e-6) -# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) - -# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) - -# if fitting_range == 'cut': - -# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) - -# tot_sam_1 = total_samp[_1] - -# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) - -# tot_sam_2 = total_samp[_2] - -# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) - -# tot_sam_3 = total_samp[_3] - -# tot_sam = np.append(tot_sam_1, tot_sam_2) -# tot_sam = np.append(tot_sam, tot_sam_3) - -# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) - -# print("Toy {}: Loading data finished".format(toy)) - -# ### Fit data - -# print("Toy {}: Fitting pdf...".format(toy)) - -# for param in total_f_fit.get_dependents(): -# param.randomize() - -# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - -# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) -# # minimizer._use_tfgrad = False -# result = minimizer.minimize(nll) - -# print("Function minimum:", result.fmin) -# print("Hesse errors:", result.hesse()) - -# params = result.params - -# if result.converged: -# Ctt_list.append(params[Ctt]['value']) -# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) - -# #plotting the result - -# plotdirName = 'data/plots'.format(toy) - -# if not os.path.exists(plotdirName): -# os.mkdir(plotdirName) -# # print("Directory " , dirName , " Created ") - -# plt.clf() -# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') -# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) - - -# probs = total_f_fit.pdf(test_q, norm_range=False) -# calcs_test = zfit.run(probs) -# plt.clf() -# plt.plot(test_q, calcs_test, label = 'pdf') -# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') -# plt.legend() -# plt.ylim(0.0, 1.5e-6) -# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) - -# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) -# print("Time taken: {}".format(display_time(int(time.time() - start)))) -# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) - - - -# In[40]: - - -# with open("data/results/Ctt_list.pkl", "wb") as f: -# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) -# with open("data/results/Ctt_error_list.pkl", "wb") as f: -# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) - - -# In[41]: - - -# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) -# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) -# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) -# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) - - -# In[42]: - - -# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) - -# plt.show() - -# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) - -# tot_sam.shape - - -# In[43]: - - -# Ctt.floating = False - - -# In[44]: - - -# zfit.run(nll.value()) - - -# In[45]: - - -# result.fmin - - -# In[46]: - - -# BR_steps = np.linspace(0.0, 1e-3, 11) - - -# # CLS Code - -# In[47]: - - -# zfit.run.numeric_checks = False - -load = False - -bo5 = True - -bo5_set = 5 - -fitting_range = 'cut' -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 -cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR - -Ctt_list = [] -Ctt_error_list = [] - -nr_of_toys = 1 -nevents = int(pdg["number_of_decays"]*cut_BR) -# nevents = pdg["number_of_decays"] -event_stack = 1000000 -# nevents *= 41 -# zfit.settings.set_verbosity(10) - -mi = 0.0 -ma = 1e-3 -ste = 11 - -BR_steps = np.linspace(mi, ma, ste) - -Ctt_steps = np.sqrt(BR_steps/4.2*1000) - -total_samp = [] - -start = time.time() - -Nll_list = [] - -sampler = total_f.create_sampler(n=nevents) - -__ = 0 - - -#----------------------------------------------------- - -if not load: - - for Ctt_step in Ctt_steps: - - __ += 1 - - newset = True - - for floaty in [True, False]: - - Ctt.floating = floaty - - Nll_list.append([]) - - if bo5: - - while len(Nll_list[-1])/bo5_set < nr_of_toys: - - print('Step: {0}/{1}'.format(__, ste)) - - print('Current Ctt: {0}'.format(Ctt_step)) - print('Ctt floating: {0}'.format(floaty)) - - print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) - - reset_param_values() - - if floaty: - Ctt.set_value(Ctt_step) - else: - Ctt.set_value(0.0) - - if newset: - sampler.resample(n=nevents) - s = sampler.unstack_x() - total_samp = zfit.run(s) - calls = 0 - c = 1 - newset = False - - - data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) - - ### Fit data - - for param in total_f_fit.get_dependents(): - param.randomize() - - nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - - minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) - # minimizer._use_tfgrad = False - result = minimizer.minimize(nll) - - # print("Function minimum:", result.fmin) - # print("Hesse errors:", result.hesse()) - - params = result.params - - if result.converged: - Nll_list[-1].append(result.fmin) - - else: - - while len(Nll_list[-1]) < nr_of_toys: - - print('Step: {0}/{1}'.format(__, ste)) - - print('Current Ctt: {0}'.format(Ctt_step)) - print('Ctt floating: {0}'.format(floaty)) - - print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) - - reset_param_values() - - if floaty: - Ctt.set_value(Ctt_step) - else: - Ctt.set_value(0.0) - - if floaty: - sampler.resample(n=nevents) - s = sampler.unstack_x() - total_samp = zfit.run(s) - calls = 0 - c = 1 - - - data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) - - ### Fit data - - for param in total_f_fit.get_dependents(): - param.randomize() - - nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) - - minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) - # minimizer._use_tfgrad = False - result = minimizer.minimize(nll) - - # print("Function minimum:", result.fmin) - # print("Hesse errors:", result.hesse()) - - params = result.params - - if result.converged: - Nll_list[-1].append(result.fmin) - - _t = int(time.time()-start) - - print('Time Taken: {}'.format(display_time(int(_t)))) - - print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) - - -# In[48]: - - -if load: - Nll_list = [] - CLs_values = [] - - _dir = 'data/CLs/finished/f1d1' - - jobs = os.listdir(_dir) - - for s in range(ste): - CLs_values.append([]) - - for s in range(2*ste): - Nll_list.append([]) - - for job in jobs: - if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): - print(job) - continue - - with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: - _Nll_list = pkl.load(input_file) - - if bo5: - for s in range(2*ste): - Nll_list[s].append(np.min(_Nll_list[s])) - else: - for s in range(2*ste): - Nll_list[s].extend(_Nll_list[s]) - - with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: - _CLs_values = pkl.load(input_file) - - for s in range(ste): - CLs_values[s].extend(_CLs_values[s]) - - print(np.shape(Nll_list)) - - -# In[50]: - - -dirName = 'data/CLs' - -# if bo5 and not load: -# for s in range(2*ste): -# Nll_list[s] = [np.min(Nll_list[s])] - -if bo5: - CLs_values= [] - for i in range(int(len(Nll_list)/2)): - CLs_values.append([]) - for j in range(len(Nll_list[0])): - CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) - - -if not load: - - CLs_values = [] - - for i in range(int(len(Nll_list)/2)): - CLs_values.append([]) - for j in range(nr_of_toys): - CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) - - if not os.path.exists(dirName): - os.mkdir(dirName) - print("Directory " , dirName , " Created ") - - with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: - pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) - - with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: - pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) - - -# In[51]: - - -# print(CLs_values) -print(Nll_list) - - -# ## Plot - -# In[52]: - - -l = [] - -for i in range(len(CLs_values)): - plt.clf() - plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) - plt.hist(CLs_values[0], bins = 100, label = 'Ctt fixed to 0') - plt.hist(CLs_values[i], bins = 100, label = 'Ctt floating') - plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=0.7, linestyle = 'dotted') - plt.legend() - plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) - - l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) - - -# In[53]: - - -for s in range(len(l)): - print('BR: {}'.format(BR_steps[s])) - print(2*l[s]/len(CLs_values[0])) - print() - - -# In[54]: - - -# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) - - -# In[ ]: - - - - diff --git a/data/CLs/finished/f1d1/2254896/test.png b/data/CLs/finished/f1d1/2254896/test.png deleted file mode 100644 index 1455457..0000000 --- a/data/CLs/finished/f1d1/2254896/test.png +++ /dev/null Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254881/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2254881/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9311452 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254881/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254881/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2254881/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..725153c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254881/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254881/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2254881/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..69f9229 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254881/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254881/data/CLs/0.0-0.001_11s--CLs_list.pkl b/data/CLs/finished/f1d1/bo5-+/2254881/data/CLs/0.0-0.001_11s--CLs_list.pkl new file mode 100644 index 0000000..1e18f87 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254881/data/CLs/0.0-0.001_11s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254881/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2254881/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254881/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2254881/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2254881/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254881/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2254881/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2254881/raremodel-nb1.py new file mode 100644 index 0000000..1a5d9be --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254881/raremodel-nb1.py @@ -0,0 +1,1939 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[47]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[48]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +if bo5: + CLs_values= [] + for i in range(int(len(Nll_list)/2)): + CLs_values.append([]) + for j in range(len(Nll_list[0])): + CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + CLs_values = [] + + for i in range(int(len(Nll_list)/2)): + CLs_values.append([]) + for j in range(nr_of_toys): + CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +print(Nll_list) + + +# ## Plot + +# In[52]: + + +l = [] + +for i in range(len(CLs_values)): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) + plt.hist(CLs_values[0], bins = 100, label = 'Ctt fixed to 0') + plt.hist(CLs_values[i], bins = 100, label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=0.7, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + + l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[53]: + + +for s in range(len(l)): + print('BR: {}'.format(BR_steps[s])) + print(2*l[s]/len(CLs_values[0])) + print() + + +# In[54]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2254881/test.png b/data/CLs/finished/f1d1/bo5-+/2254881/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254881/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254886/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2254886/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..00db4a8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254886/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254886/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2254886/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d09bea0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254886/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254886/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2254886/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3a2bb99 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254886/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254886/data/CLs/0.0-0.001_11s--CLs_list.pkl b/data/CLs/finished/f1d1/bo5-+/2254886/data/CLs/0.0-0.001_11s--CLs_list.pkl new file mode 100644 index 0000000..1414d37 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254886/data/CLs/0.0-0.001_11s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254886/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2254886/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254886/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2254886/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2254886/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254886/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2254886/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2254886/raremodel-nb1.py new file mode 100644 index 0000000..1a5d9be --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254886/raremodel-nb1.py @@ -0,0 +1,1939 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[47]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[48]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +if bo5: + CLs_values= [] + for i in range(int(len(Nll_list)/2)): + CLs_values.append([]) + for j in range(len(Nll_list[0])): + CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + CLs_values = [] + + for i in range(int(len(Nll_list)/2)): + CLs_values.append([]) + for j in range(nr_of_toys): + CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +print(Nll_list) + + +# ## Plot + +# In[52]: + + +l = [] + +for i in range(len(CLs_values)): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) + plt.hist(CLs_values[0], bins = 100, label = 'Ctt fixed to 0') + plt.hist(CLs_values[i], bins = 100, label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=0.7, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + + l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[53]: + + +for s in range(len(l)): + print('BR: {}'.format(BR_steps[s])) + print(2*l[s]/len(CLs_values[0])) + print() + + +# In[54]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2254886/test.png b/data/CLs/finished/f1d1/bo5-+/2254886/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254886/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254891/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2254891/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ac2b0f3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254891/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254891/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2254891/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..499d38c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254891/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254891/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2254891/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ceaff27 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254891/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254891/data/CLs/0.0-0.001_11s--CLs_list.pkl b/data/CLs/finished/f1d1/bo5-+/2254891/data/CLs/0.0-0.001_11s--CLs_list.pkl new file mode 100644 index 0000000..f0e7330 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254891/data/CLs/0.0-0.001_11s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254891/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2254891/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254891/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2254891/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2254891/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254891/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2254891/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2254891/raremodel-nb1.py new file mode 100644 index 0000000..1a5d9be --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254891/raremodel-nb1.py @@ -0,0 +1,1939 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[47]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[48]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +if bo5: + CLs_values= [] + for i in range(int(len(Nll_list)/2)): + CLs_values.append([]) + for j in range(len(Nll_list[0])): + CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + CLs_values = [] + + for i in range(int(len(Nll_list)/2)): + CLs_values.append([]) + for j in range(nr_of_toys): + CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +print(Nll_list) + + +# ## Plot + +# In[52]: + + +l = [] + +for i in range(len(CLs_values)): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) + plt.hist(CLs_values[0], bins = 100, label = 'Ctt fixed to 0') + plt.hist(CLs_values[i], bins = 100, label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=0.7, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + + l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[53]: + + +for s in range(len(l)): + print('BR: {}'.format(BR_steps[s])) + print(2*l[s]/len(CLs_values[0])) + print() + + +# In[54]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2254891/test.png b/data/CLs/finished/f1d1/bo5-+/2254891/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254891/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254896/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2254896/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..30cf970 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254896/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254896/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2254896/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4d627a4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254896/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254896/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2254896/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f1667f8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254896/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254896/data/CLs/0.0-0.001_11s--CLs_list.pkl b/data/CLs/finished/f1d1/bo5-+/2254896/data/CLs/0.0-0.001_11s--CLs_list.pkl new file mode 100644 index 0000000..f517f52 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254896/data/CLs/0.0-0.001_11s--CLs_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2254896/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2254896/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254896/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2254896/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2254896/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254896/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2254896/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2254896/raremodel-nb1.py new file mode 100644 index 0000000..1a5d9be --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254896/raremodel-nb1.py @@ -0,0 +1,1939 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[47]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[48]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +if bo5: + CLs_values= [] + for i in range(int(len(Nll_list)/2)): + CLs_values.append([]) + for j in range(len(Nll_list[0])): + CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + CLs_values = [] + + for i in range(int(len(Nll_list)/2)): + CLs_values.append([]) + for j in range(nr_of_toys): + CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + + with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +print(Nll_list) + + +# ## Plot + +# In[52]: + + +l = [] + +for i in range(len(CLs_values)): + plt.clf() + plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) + plt.hist(CLs_values[0], bins = 100, label = 'Ctt fixed to 0') + plt.hist(CLs_values[i], bins = 100, label = 'Ctt floating') + plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=0.7, linestyle = 'dotted') + plt.legend() + plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + + l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[53]: + + +for s in range(len(l)): + print('BR: {}'.format(BR_steps[s])) + print(2*l[s]/len(CLs_values[0])) + print() + + +# In[54]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2254896/test.png b/data/CLs/finished/f1d1/bo5-+/2254896/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2254896/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256819/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256819/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..54ac337 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256819/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256819/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256819/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..498ca9e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256819/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256819/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256819/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..51482a7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256819/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256819/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256819/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256819/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256819/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256819/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256819/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256819/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256819/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256819/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256819/test.png b/data/CLs/finished/f1d1/bo5-+/2256819/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256819/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256820/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256820/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c555000 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256820/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256820/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256820/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8518ec8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256820/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256820/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256820/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..6acc987 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256820/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256820/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256820/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256820/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256820/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256820/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256820/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256820/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256820/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256820/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256820/test.png b/data/CLs/finished/f1d1/bo5-+/2256820/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256820/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256821/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256821/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..79bbfb5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256821/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256821/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256821/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d66d3c5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256821/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256821/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256821/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..cb382d4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256821/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256821/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256821/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256821/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256821/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256821/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256821/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256821/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256821/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256821/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256821/test.png b/data/CLs/finished/f1d1/bo5-+/2256821/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256821/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256822/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256822/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4a23a4b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256822/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256822/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256822/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0d3d489 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256822/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256822/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256822/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..56ad1cc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256822/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256822/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256822/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256822/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256822/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256822/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256822/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256822/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256822/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256822/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256822/test.png b/data/CLs/finished/f1d1/bo5-+/2256822/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256822/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256823/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256823/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4577fd2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256823/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256823/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256823/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8b71ec9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256823/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256823/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256823/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e8e2391 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256823/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256823/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256823/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256823/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256823/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256823/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256823/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256823/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256823/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256823/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256823/test.png b/data/CLs/finished/f1d1/bo5-+/2256823/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256823/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256824/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256824/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bf75000 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256824/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256824/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256824/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..beb9001 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256824/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256824/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256824/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..bdf460e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256824/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256824/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256824/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256824/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256824/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256824/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256824/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256824/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256824/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256824/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256824/test.png b/data/CLs/finished/f1d1/bo5-+/2256824/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256824/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256825/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256825/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e6d8b27 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256825/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256825/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256825/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b8919b9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256825/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256825/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256825/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4a82b1c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256825/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256825/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256825/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256825/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256825/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256825/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256825/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256825/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256825/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256825/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256825/test.png b/data/CLs/finished/f1d1/bo5-+/2256825/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256825/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256826/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256826/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..67dc1d8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256826/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256826/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256826/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4832bba --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256826/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256826/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256826/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3969545 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256826/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256826/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256826/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256826/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256826/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256826/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256826/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256826/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256826/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256826/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256826/test.png b/data/CLs/finished/f1d1/bo5-+/2256826/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256826/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256827/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256827/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..aba9e8b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256827/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256827/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256827/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..92dd475 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256827/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256827/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256827/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ccd2210 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256827/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256827/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256827/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256827/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256827/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256827/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256827/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256827/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256827/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256827/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256827/test.png b/data/CLs/finished/f1d1/bo5-+/2256827/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256827/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256828/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256828/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..20782a9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256828/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256828/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256828/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..82aeee4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256828/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256828/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256828/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a8404e2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256828/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256828/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256828/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256828/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256828/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256828/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256828/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256828/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256828/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256828/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256828/test.png b/data/CLs/finished/f1d1/bo5-+/2256828/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256828/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256829/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256829/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5be2470 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256829/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256829/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256829/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..6eb12aa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256829/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256829/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256829/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b85fda2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256829/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256829/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256829/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256829/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256829/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256829/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256829/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256829/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256829/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256829/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256829/test.png b/data/CLs/finished/f1d1/bo5-+/2256829/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256829/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256830/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256830/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d4f2352 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256830/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256830/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256830/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..6338dc5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256830/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256830/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256830/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7c0e9cb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256830/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256830/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256830/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256830/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256830/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256830/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256830/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256830/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256830/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256830/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256830/test.png b/data/CLs/finished/f1d1/bo5-+/2256830/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256830/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256831/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256831/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..89097a9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256831/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256831/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256831/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..11d8da3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256831/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256831/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256831/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c8b3a83 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256831/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256831/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256831/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256831/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256831/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256831/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256831/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256831/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256831/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256831/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256831/test.png b/data/CLs/finished/f1d1/bo5-+/2256831/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256831/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256832/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256832/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0154fc4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256832/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256832/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256832/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d9002c8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256832/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256832/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256832/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..1d50deb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256832/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256832/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256832/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256832/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256832/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256832/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256832/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256832/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256832/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256832/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256832/test.png b/data/CLs/finished/f1d1/bo5-+/2256832/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256832/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256833/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256833/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..080b2da --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256833/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256833/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256833/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d3b5ca9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256833/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256833/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256833/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..dce445a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256833/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256833/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256833/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256833/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256833/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256833/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256833/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256833/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256833/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256833/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256833/test.png b/data/CLs/finished/f1d1/bo5-+/2256833/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256833/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256834/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256834/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..58e6bda --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256834/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256834/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256834/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..153ed1f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256834/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256834/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256834/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2d8b9f4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256834/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256834/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256834/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256834/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256834/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256834/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256834/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256834/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256834/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256834/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256834/test.png b/data/CLs/finished/f1d1/bo5-+/2256834/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256834/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256835/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256835/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0c8ebeb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256835/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256835/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256835/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8ab706a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256835/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256835/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256835/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..64fbccb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256835/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256835/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256835/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256835/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256835/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256835/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256835/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256835/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256835/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256835/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256835/test.png b/data/CLs/finished/f1d1/bo5-+/2256835/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256835/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256836/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256836/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..28b4800 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256836/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256836/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256836/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..883c7f4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256836/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256836/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256836/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..022fbba --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256836/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256836/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256836/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256836/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256836/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256836/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256836/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256836/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256836/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256836/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256836/test.png b/data/CLs/finished/f1d1/bo5-+/2256836/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256836/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256837/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256837/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9bcc046 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256837/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256837/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256837/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4dbaf4b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256837/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256837/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256837/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7667da4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256837/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256837/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256837/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256837/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256837/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256837/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256837/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256837/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256837/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256837/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256837/test.png b/data/CLs/finished/f1d1/bo5-+/2256837/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256837/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256838/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256838/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d037486 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256838/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256838/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256838/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..08817dd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256838/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256838/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256838/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..59169e4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256838/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256838/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256838/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256838/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256838/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256838/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256838/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256838/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256838/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256838/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256838/test.png b/data/CLs/finished/f1d1/bo5-+/2256838/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256838/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256839/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256839/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c2732f6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256839/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256839/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256839/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0bafeb8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256839/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256839/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256839/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..6effe1a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256839/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256839/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256839/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256839/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256839/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256839/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256839/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256839/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256839/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256839/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256839/test.png b/data/CLs/finished/f1d1/bo5-+/2256839/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256839/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256840/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256840/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4ff935c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256840/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256840/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256840/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c70c298 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256840/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256840/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256840/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8701629 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256840/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256840/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256840/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256840/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256840/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256840/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256840/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256840/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256840/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256840/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256840/test.png b/data/CLs/finished/f1d1/bo5-+/2256840/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256840/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256841/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256841/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..294d760 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256841/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256841/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256841/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..45d86f0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256841/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256841/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256841/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..986dc15 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256841/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256841/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256841/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256841/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256841/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256841/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256841/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256841/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256841/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256841/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256841/test.png b/data/CLs/finished/f1d1/bo5-+/2256841/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256841/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256842/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256842/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9cb97d8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256842/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256842/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256842/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b082038 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256842/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256842/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256842/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f4dc95f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256842/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256842/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256842/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256842/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256842/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256842/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256842/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256842/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256842/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256842/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256842/test.png b/data/CLs/finished/f1d1/bo5-+/2256842/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256842/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256843/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256843/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5783a26 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256843/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256843/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256843/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..38a8bec --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256843/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256843/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256843/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..727120e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256843/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256843/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256843/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256843/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256843/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256843/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256843/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256843/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256843/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256843/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256843/test.png b/data/CLs/finished/f1d1/bo5-+/2256843/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256843/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256844/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256844/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9ed913b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256844/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256844/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256844/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4cb2263 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256844/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256844/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256844/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..cb5b9f6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256844/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256844/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256844/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256844/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256844/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256844/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256844/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256844/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256844/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256844/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256844/test.png b/data/CLs/finished/f1d1/bo5-+/2256844/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256844/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256845/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256845/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0c34453 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256845/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256845/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256845/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..23d8807 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256845/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256845/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256845/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d28b629 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256845/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256845/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256845/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256845/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256845/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256845/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256845/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256845/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256845/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256845/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256845/test.png b/data/CLs/finished/f1d1/bo5-+/2256845/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256845/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256846/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256846/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..43156e3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256846/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256846/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256846/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2c598b1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256846/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256846/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256846/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..16c4b2d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256846/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256846/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256846/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256846/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256846/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256846/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256846/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256846/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256846/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256846/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256846/test.png b/data/CLs/finished/f1d1/bo5-+/2256846/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256846/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256847/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256847/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a211dfc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256847/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256847/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256847/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..58247aa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256847/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256847/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256847/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f6629e1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256847/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256847/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256847/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256847/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256847/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256847/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256847/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256847/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256847/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256847/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256847/test.png b/data/CLs/finished/f1d1/bo5-+/2256847/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256847/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256848/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256848/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..91023c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256848/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256848/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256848/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5126ef4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256848/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256848/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256848/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..05b63a2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256848/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256848/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256848/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256848/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256848/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256848/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256848/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256848/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256848/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256848/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256848/test.png b/data/CLs/finished/f1d1/bo5-+/2256848/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256848/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256849/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256849/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..968c512 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256849/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256849/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256849/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..36893d7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256849/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256849/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256849/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f531f21 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256849/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256849/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256849/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256849/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256849/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256849/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256849/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256849/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256849/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256849/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256849/test.png b/data/CLs/finished/f1d1/bo5-+/2256849/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256849/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256850/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256850/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f2349eb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256850/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256850/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256850/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..196ae17 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256850/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256850/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256850/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0ec1953 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256850/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256850/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256850/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256850/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256850/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256850/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256850/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256850/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256850/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256850/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256850/test.png b/data/CLs/finished/f1d1/bo5-+/2256850/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256850/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256851/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256851/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..69d557e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256851/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256851/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256851/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..eaab9bc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256851/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256851/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256851/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f6679c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256851/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256851/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256851/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256851/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256851/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256851/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256851/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256851/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256851/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256851/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256851/test.png b/data/CLs/finished/f1d1/bo5-+/2256851/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256851/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256852/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256852/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..db2061a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256852/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256852/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256852/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b20f013 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256852/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256852/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256852/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a5b0f1e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256852/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256852/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256852/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256852/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256852/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256852/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256852/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256852/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256852/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256852/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256852/test.png b/data/CLs/finished/f1d1/bo5-+/2256852/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256852/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256853/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256853/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f1da61c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256853/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256853/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256853/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5cd1bb1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256853/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256853/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256853/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..889b6e6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256853/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256853/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256853/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256853/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256853/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256853/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256853/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256853/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256853/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256853/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256853/test.png b/data/CLs/finished/f1d1/bo5-+/2256853/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256853/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256854/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256854/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3dc5fc4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256854/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256854/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256854/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a1f0a40 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256854/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256854/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256854/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ef9a800 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256854/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256854/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256854/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256854/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256854/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256854/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256854/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256854/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256854/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256854/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256854/test.png b/data/CLs/finished/f1d1/bo5-+/2256854/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256854/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256855/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256855/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c1db7e1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256855/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256855/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256855/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5e845ce --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256855/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256855/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256855/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..94c4f02 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256855/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256855/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256855/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256855/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256855/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256855/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256855/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256855/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256855/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256855/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256855/test.png b/data/CLs/finished/f1d1/bo5-+/2256855/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256855/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256856/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256856/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b75e964 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256856/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256856/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256856/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..338f257 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256856/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256856/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256856/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5a132ae --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256856/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256856/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256856/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256856/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256856/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256856/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256856/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256856/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256856/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256856/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256856/test.png b/data/CLs/finished/f1d1/bo5-+/2256856/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256856/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256857/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256857/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6c7c1d2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256857/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256857/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256857/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c9cadfb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256857/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256857/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256857/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d2f4ca6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256857/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256857/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256857/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256857/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256857/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256857/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256857/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256857/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256857/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256857/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256857/test.png b/data/CLs/finished/f1d1/bo5-+/2256857/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256857/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256858/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256858/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b60d0d0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256858/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256858/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256858/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b4adae1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256858/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256858/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256858/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..aa8daef --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256858/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256858/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256858/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256858/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256858/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256858/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256858/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256858/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256858/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256858/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256858/test.png b/data/CLs/finished/f1d1/bo5-+/2256858/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256858/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256859/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256859/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7e06936 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256859/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256859/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256859/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3b02512 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256859/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256859/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256859/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..75c95f9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256859/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256859/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256859/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256859/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256859/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256859/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256859/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256859/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256859/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256859/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256859/test.png b/data/CLs/finished/f1d1/bo5-+/2256859/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256859/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256860/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256860/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6fe9e85 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256860/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256860/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256860/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5801643 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256860/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256860/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256860/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e0fd23d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256860/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256860/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256860/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256860/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256860/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256860/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256860/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256860/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256860/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256860/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256860/test.png b/data/CLs/finished/f1d1/bo5-+/2256860/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256860/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256861/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256861/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..86ccdf7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256861/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256861/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256861/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b10509e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256861/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256861/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256861/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..63a210b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256861/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256861/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256861/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256861/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256861/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256861/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256861/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256861/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256861/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256861/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256861/test.png b/data/CLs/finished/f1d1/bo5-+/2256861/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256861/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256862/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256862/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..56e7b5a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256862/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256862/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256862/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fb3ce59 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256862/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256862/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256862/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..11f391e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256862/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256862/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256862/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256862/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256862/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256862/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256862/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256862/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256862/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256862/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256862/test.png b/data/CLs/finished/f1d1/bo5-+/2256862/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256862/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256863/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256863/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9b1ab53 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256863/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256863/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256863/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..750109b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256863/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256863/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256863/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..6a55fa4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256863/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256863/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256863/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256863/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256863/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256863/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256863/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256863/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256863/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256863/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256863/test.png b/data/CLs/finished/f1d1/bo5-+/2256863/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256863/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256864/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256864/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fbb9efa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256864/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256864/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256864/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3e6c962 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256864/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256864/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256864/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..91073cc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256864/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256864/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256864/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256864/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256864/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256864/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256864/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256864/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256864/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256864/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256864/test.png b/data/CLs/finished/f1d1/bo5-+/2256864/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256864/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256865/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256865/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cf5d752 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256865/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256865/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256865/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cf023ec --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256865/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256865/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256865/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7e0e914 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256865/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256865/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256865/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256865/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256865/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256865/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256865/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256865/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256865/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256865/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256865/test.png b/data/CLs/finished/f1d1/bo5-+/2256865/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256865/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256866/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256866/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f074365 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256866/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256866/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256866/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5e4b17d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256866/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256866/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256866/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4368d09 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256866/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256866/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256866/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256866/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256866/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256866/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256866/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256866/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256866/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256866/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256866/test.png b/data/CLs/finished/f1d1/bo5-+/2256866/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256866/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256867/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256867/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..aac0984 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256867/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256867/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256867/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ccad1fb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256867/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256867/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256867/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..514e24a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256867/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256867/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256867/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256867/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256867/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256867/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256867/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256867/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256867/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256867/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256867/test.png b/data/CLs/finished/f1d1/bo5-+/2256867/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256867/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256868/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256868/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..050762d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256868/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256868/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256868/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..93f6ca5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256868/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256868/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256868/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8387377 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256868/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256868/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256868/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256868/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256868/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256868/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256868/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256868/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256868/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256868/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256868/test.png b/data/CLs/finished/f1d1/bo5-+/2256868/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256868/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256869/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256869/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..59f62cb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256869/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256869/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256869/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9cff10b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256869/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256869/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256869/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..93c9146 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256869/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256869/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256869/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256869/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256869/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256869/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256869/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256869/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256869/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256869/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256869/test.png b/data/CLs/finished/f1d1/bo5-+/2256869/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256869/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256870/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256870/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e86eb55 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256870/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256870/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256870/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0f3320b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256870/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256870/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256870/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..fc99cbc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256870/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256870/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256870/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256870/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256870/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256870/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256870/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256870/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256870/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256870/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256870/test.png b/data/CLs/finished/f1d1/bo5-+/2256870/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256870/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256871/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256871/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4c05729 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256871/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256871/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256871/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8e8b47a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256871/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256871/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256871/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..fda79de --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256871/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256871/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256871/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256871/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256871/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256871/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256871/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256871/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256871/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256871/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256871/test.png b/data/CLs/finished/f1d1/bo5-+/2256871/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256871/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256872/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256872/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cf50f59 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256872/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256872/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256872/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d0067ab --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256872/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256872/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256872/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9c65893 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256872/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256872/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256872/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256872/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256872/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256872/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256872/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256872/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256872/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256872/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256872/test.png b/data/CLs/finished/f1d1/bo5-+/2256872/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256872/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256873/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256873/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..735929f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256873/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256873/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256873/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5474521 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256873/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256873/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256873/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d7bf879 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256873/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256873/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256873/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256873/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256873/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256873/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256873/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256873/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256873/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256873/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256873/test.png b/data/CLs/finished/f1d1/bo5-+/2256873/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256873/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256874/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256874/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dc0c823 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256874/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256874/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256874/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..6bf7a17 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256874/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256874/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256874/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4740314 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256874/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256874/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256874/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256874/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256874/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256874/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256874/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256874/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256874/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256874/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256874/test.png b/data/CLs/finished/f1d1/bo5-+/2256874/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256874/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256875/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256875/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7fdf8a6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256875/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256875/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256875/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..76acff5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256875/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256875/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256875/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f681b21 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256875/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256875/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256875/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256875/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256875/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256875/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256875/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256875/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256875/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256875/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256875/test.png b/data/CLs/finished/f1d1/bo5-+/2256875/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256875/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256876/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256876/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dbe02d0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256876/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256876/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256876/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..bd0e901 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256876/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256876/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256876/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c4ef42a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256876/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256876/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256876/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256876/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256876/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256876/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256876/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256876/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256876/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256876/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256876/test.png b/data/CLs/finished/f1d1/bo5-+/2256876/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256876/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256877/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256877/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8a81067 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256877/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256877/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256877/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..71ddc38 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256877/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256877/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256877/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f061944 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256877/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256877/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256877/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256877/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256877/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256877/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256877/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256877/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256877/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256877/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256877/test.png b/data/CLs/finished/f1d1/bo5-+/2256877/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256877/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256878/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256878/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2ea06f0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256878/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256878/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256878/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2969af1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256878/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256878/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256878/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4eaad32 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256878/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256878/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256878/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256878/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256878/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256878/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256878/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256878/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256878/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256878/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256878/test.png b/data/CLs/finished/f1d1/bo5-+/2256878/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256878/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256879/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256879/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d27c3e7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256879/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256879/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256879/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..74de60d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256879/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256879/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256879/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..6a8d80f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256879/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256879/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256879/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256879/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256879/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256879/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256879/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256879/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256879/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256879/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256879/test.png b/data/CLs/finished/f1d1/bo5-+/2256879/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256879/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256880/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256880/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cfdde76 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256880/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256880/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256880/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..39f71b6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256880/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256880/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256880/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..bd7da3b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256880/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256880/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256880/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256880/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256880/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256880/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256880/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256880/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256880/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256880/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256880/test.png b/data/CLs/finished/f1d1/bo5-+/2256880/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256880/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256881/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256881/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a9b6d9f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256881/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256881/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256881/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2d39ef9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256881/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256881/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256881/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..6fefd6e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256881/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256881/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256881/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256881/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256881/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256881/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256881/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256881/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256881/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256881/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256881/test.png b/data/CLs/finished/f1d1/bo5-+/2256881/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256881/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256882/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256882/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fe425e3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256882/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256882/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256882/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7af4dca --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256882/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256882/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256882/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b83b941 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256882/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256882/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256882/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256882/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256882/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256882/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256882/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256882/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256882/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256882/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256882/test.png b/data/CLs/finished/f1d1/bo5-+/2256882/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256882/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256883/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256883/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..793520c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256883/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256883/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256883/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..891116f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256883/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256883/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256883/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..6a9d909 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256883/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256883/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256883/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256883/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256883/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256883/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256883/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256883/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256883/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256883/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256883/test.png b/data/CLs/finished/f1d1/bo5-+/2256883/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256883/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256884/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256884/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8aeddb6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256884/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256884/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256884/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4e35664 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256884/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256884/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256884/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..93a8fce --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256884/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256884/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256884/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256884/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256884/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256884/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256884/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256884/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256884/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256884/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256884/test.png b/data/CLs/finished/f1d1/bo5-+/2256884/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256884/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256885/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256885/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..80f1501 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256885/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256885/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256885/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4a74c94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256885/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256885/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256885/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..fa8734e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256885/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256885/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256885/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256885/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256885/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256885/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256885/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256885/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256885/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256885/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256885/test.png b/data/CLs/finished/f1d1/bo5-+/2256885/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256885/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256886/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256886/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7ede9c9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256886/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256886/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256886/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..923d0aa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256886/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256886/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256886/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..40906fa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256886/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256886/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256886/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256886/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256886/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256886/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256886/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256886/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256886/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256886/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256886/test.png b/data/CLs/finished/f1d1/bo5-+/2256886/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256886/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256887/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256887/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4371b48 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256887/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256887/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256887/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b1a1e97 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256887/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256887/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256887/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0377a54 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256887/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256887/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256887/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256887/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256887/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256887/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256887/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256887/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256887/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256887/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256887/test.png b/data/CLs/finished/f1d1/bo5-+/2256887/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256887/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256888/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256888/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8e60b5b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256888/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256888/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256888/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d7f76e3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256888/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256888/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256888/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e6e1aba --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256888/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256888/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256888/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256888/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256888/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256888/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256888/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256888/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256888/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256888/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256888/test.png b/data/CLs/finished/f1d1/bo5-+/2256888/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256888/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256889/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256889/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..be040b5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256889/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256889/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256889/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0569e10 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256889/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256889/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256889/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..abfc016 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256889/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256889/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256889/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256889/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256889/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256889/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256889/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256889/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256889/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256889/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256889/test.png b/data/CLs/finished/f1d1/bo5-+/2256889/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256889/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256890/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256890/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..60285c3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256890/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256890/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256890/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7f42901 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256890/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256890/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256890/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b00ac57 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256890/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256890/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256890/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256890/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256890/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256890/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256890/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256890/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256890/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256890/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256890/test.png b/data/CLs/finished/f1d1/bo5-+/2256890/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256890/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256891/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256891/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..928d83e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256891/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256891/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256891/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cf43c0c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256891/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256891/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256891/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2015c65 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256891/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256891/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256891/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256891/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256891/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256891/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256891/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256891/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256891/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256891/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256891/test.png b/data/CLs/finished/f1d1/bo5-+/2256891/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256891/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256892/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256892/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2863bc5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256892/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256892/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256892/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5997e79 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256892/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256892/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256892/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4752008 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256892/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256892/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256892/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256892/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256892/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256892/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256892/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256892/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256892/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256892/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256892/test.png b/data/CLs/finished/f1d1/bo5-+/2256892/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256892/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256893/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256893/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9c3c560 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256893/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256893/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256893/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a8175a8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256893/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256893/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256893/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8f589b9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256893/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256893/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256893/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256893/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256893/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256893/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256893/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256893/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256893/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256893/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256893/test.png b/data/CLs/finished/f1d1/bo5-+/2256893/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256893/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256894/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256894/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..81e4f01 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256894/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256894/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256894/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7817434 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256894/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256894/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256894/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8684e92 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256894/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256894/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256894/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256894/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256894/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256894/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256894/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256894/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256894/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256894/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256894/test.png b/data/CLs/finished/f1d1/bo5-+/2256894/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256894/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256895/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256895/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0b96b34 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256895/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256895/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256895/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c24be15 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256895/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256895/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256895/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..bd06417 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256895/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256895/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256895/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256895/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256895/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256895/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256895/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256895/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256895/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256895/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256895/test.png b/data/CLs/finished/f1d1/bo5-+/2256895/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256895/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256896/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256896/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..17ed1a8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256896/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256896/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256896/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..40c1de0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256896/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256896/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256896/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..650f808 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256896/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256896/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256896/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256896/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256896/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256896/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256896/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256896/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256896/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256896/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256896/test.png b/data/CLs/finished/f1d1/bo5-+/2256896/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256896/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256897/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256897/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2b365fe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256897/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256897/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256897/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f2cc1b7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256897/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256897/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256897/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ff61055 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256897/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256897/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256897/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256897/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256897/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256897/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256897/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256897/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256897/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256897/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256897/test.png b/data/CLs/finished/f1d1/bo5-+/2256897/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256897/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256898/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256898/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..87a565a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256898/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256898/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256898/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b5b0df6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256898/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256898/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256898/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2ff4679 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256898/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256898/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256898/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256898/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256898/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256898/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256898/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256898/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256898/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256898/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256898/test.png b/data/CLs/finished/f1d1/bo5-+/2256898/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256898/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256899/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256899/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..09f2508 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256899/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256899/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256899/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2355e8b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256899/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256899/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256899/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c233d5e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256899/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256899/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256899/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256899/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256899/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256899/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256899/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256899/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256899/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256899/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256899/test.png b/data/CLs/finished/f1d1/bo5-+/2256899/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256899/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256900/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256900/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..14f8e2e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256900/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256900/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256900/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b390b93 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256900/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256900/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256900/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..84de76f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256900/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256900/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256900/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256900/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256900/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256900/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256900/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256900/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256900/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256900/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256900/test.png b/data/CLs/finished/f1d1/bo5-+/2256900/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256900/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256901/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256901/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d4f1fd0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256901/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256901/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256901/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f5a9c5e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256901/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256901/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256901/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5fa979b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256901/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256901/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256901/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256901/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256901/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256901/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256901/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256901/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256901/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256901/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256901/test.png b/data/CLs/finished/f1d1/bo5-+/2256901/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256901/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256902/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256902/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ce82f53 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256902/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256902/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256902/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1319a5c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256902/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256902/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256902/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..dbbd2b7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256902/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256902/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256902/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256902/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256902/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256902/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256902/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256902/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256902/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256902/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256902/test.png b/data/CLs/finished/f1d1/bo5-+/2256902/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256902/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256903/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256903/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ec930dc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256903/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256903/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256903/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..43339e7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256903/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256903/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256903/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..18823b8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256903/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256903/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256903/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256903/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256903/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256903/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256903/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256903/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256903/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256903/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256903/test.png b/data/CLs/finished/f1d1/bo5-+/2256903/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256903/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256904/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256904/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f337a88 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256904/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256904/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256904/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..6014589 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256904/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256904/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256904/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b80be0e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256904/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256904/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256904/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256904/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256904/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256904/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256904/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256904/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256904/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256904/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256904/test.png b/data/CLs/finished/f1d1/bo5-+/2256904/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256904/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256905/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256905/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..396e9fc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256905/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256905/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256905/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..629b29c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256905/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256905/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256905/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2b9f2e7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256905/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256905/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256905/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256905/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256905/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256905/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256905/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256905/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256905/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256905/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256905/test.png b/data/CLs/finished/f1d1/bo5-+/2256905/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256905/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256906/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256906/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..99d1b6d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256906/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256906/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256906/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..efc3ccc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256906/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256906/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256906/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a697b52 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256906/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256906/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256906/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256906/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256906/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256906/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256906/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256906/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256906/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256906/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256906/test.png b/data/CLs/finished/f1d1/bo5-+/2256906/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256906/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256907/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256907/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..673be3f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256907/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256907/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256907/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fd13c03 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256907/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256907/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256907/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..258db6d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256907/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256907/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256907/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256907/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256907/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256907/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256907/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256907/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256907/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256907/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256907/test.png b/data/CLs/finished/f1d1/bo5-+/2256907/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256907/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256908/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256908/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4778196 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256908/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256908/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256908/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..dd91945 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256908/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256908/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256908/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5ba8fa1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256908/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256908/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256908/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256908/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256908/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256908/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256908/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256908/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256908/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256908/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256908/test.png b/data/CLs/finished/f1d1/bo5-+/2256908/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256908/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256909/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256909/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4f14775 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256909/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256909/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256909/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cce901a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256909/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256909/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256909/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..848a228 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256909/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256909/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256909/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256909/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256909/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256909/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256909/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256909/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256909/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256909/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256909/test.png b/data/CLs/finished/f1d1/bo5-+/2256909/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256909/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256910/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256910/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0bbf94e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256910/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256910/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256910/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2508c83 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256910/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256910/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256910/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4d2ea6e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256910/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256910/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256910/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256910/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256910/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256910/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256910/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256910/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256910/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256910/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256910/test.png b/data/CLs/finished/f1d1/bo5-+/2256910/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256910/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256911/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256911/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0937140 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256911/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256911/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256911/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cf2be43 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256911/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256911/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256911/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2816c42 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256911/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256911/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256911/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256911/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256911/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256911/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256911/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256911/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256911/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256911/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256911/test.png b/data/CLs/finished/f1d1/bo5-+/2256911/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256911/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256912/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256912/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..06c2799 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256912/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256912/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256912/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5d043c5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256912/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256912/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256912/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..31c12bf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256912/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256912/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256912/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256912/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256912/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256912/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256912/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256912/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256912/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256912/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256912/test.png b/data/CLs/finished/f1d1/bo5-+/2256912/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256912/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256913/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256913/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..889966e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256913/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256913/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256913/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f3abe00 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256913/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256913/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256913/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2bb3659 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256913/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256913/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256913/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256913/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256913/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256913/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256913/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256913/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256913/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256913/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256913/test.png b/data/CLs/finished/f1d1/bo5-+/2256913/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256913/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256914/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256914/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d9f9b47 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256914/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256914/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256914/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b4796d7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256914/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256914/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256914/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..91ce8b6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256914/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256914/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256914/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256914/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256914/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256914/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256914/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256914/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256914/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256914/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256914/test.png b/data/CLs/finished/f1d1/bo5-+/2256914/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256914/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256915/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256915/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..753a6c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256915/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256915/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256915/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c462eda --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256915/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256915/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256915/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7c0e10e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256915/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256915/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256915/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256915/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256915/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256915/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256915/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256915/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256915/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256915/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256915/test.png b/data/CLs/finished/f1d1/bo5-+/2256915/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256915/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256916/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256916/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ca2e376 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256916/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256916/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256916/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f86a82a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256916/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256916/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256916/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a3ed40b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256916/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256916/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256916/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256916/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256916/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256916/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256916/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256916/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256916/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256916/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256916/test.png b/data/CLs/finished/f1d1/bo5-+/2256916/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256916/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256917/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256917/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e0b8208 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256917/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256917/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256917/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1fcc873 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256917/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256917/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256917/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5a45abe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256917/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256917/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256917/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256917/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256917/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256917/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256917/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256917/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256917/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256917/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256917/test.png b/data/CLs/finished/f1d1/bo5-+/2256917/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256917/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256918/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256918/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e812db9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256918/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256918/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256918/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9655776 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256918/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256918/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256918/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d453c45 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256918/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256918/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256918/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256918/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256918/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256918/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256918/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256918/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2256918/raremodel-nb.py new file mode 100644 index 0000000..b7baeb4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256918/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256918/test.png b/data/CLs/finished/f1d1/bo5-+/2256918/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256918/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256919/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256919/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a939238 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256919/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256919/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256919/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..602c4eb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256919/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256919/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256919/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e68799f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256919/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256919/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256919/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256919/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256919/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256919/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256919/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256919/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256919/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256919/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256919/test.png b/data/CLs/finished/f1d1/bo5-+/2256919/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256919/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256920/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256920/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7afcbfe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256920/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256920/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256920/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1e4609a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256920/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256920/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256920/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d7fb37f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256920/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256920/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256920/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256920/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256920/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256920/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256920/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256920/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256920/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256920/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256920/test.png b/data/CLs/finished/f1d1/bo5-+/2256920/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256920/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256921/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256921/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6167023 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256921/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256921/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256921/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b4f9433 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256921/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256921/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256921/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3f7ecb9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256921/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256921/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256921/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256921/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256921/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256921/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256921/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256921/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256921/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256921/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256921/test.png b/data/CLs/finished/f1d1/bo5-+/2256921/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256921/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256922/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256922/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8bdbe05 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256922/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256922/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256922/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ea57780 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256922/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256922/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256922/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..6a84bed --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256922/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256922/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256922/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256922/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256922/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256922/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256922/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256922/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256922/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256922/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256922/test.png b/data/CLs/finished/f1d1/bo5-+/2256922/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256922/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256923/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256923/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..217f5a6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256923/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256923/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256923/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8de3b5a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256923/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256923/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256923/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d0ff928 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256923/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256923/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256923/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256923/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256923/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256923/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256923/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256923/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256923/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256923/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256923/test.png b/data/CLs/finished/f1d1/bo5-+/2256923/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256923/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256924/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256924/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6bf698d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256924/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256924/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256924/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d9056d3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256924/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256924/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256924/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..08b5950 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256924/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256924/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256924/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256924/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256924/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256924/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256924/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256924/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256924/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256924/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256924/test.png b/data/CLs/finished/f1d1/bo5-+/2256924/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256924/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256925/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256925/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..879fb99 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256925/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256925/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256925/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3fa7458 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256925/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256925/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256925/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d541aee --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256925/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256925/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256925/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256925/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256925/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256925/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256925/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256925/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256925/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256925/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256925/test.png b/data/CLs/finished/f1d1/bo5-+/2256925/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256925/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256926/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256926/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2aebd90 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256926/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256926/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256926/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d388318 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256926/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256926/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256926/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..de7beb2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256926/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256926/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256926/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256926/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256926/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256926/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256926/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256926/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256926/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256926/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256926/test.png b/data/CLs/finished/f1d1/bo5-+/2256926/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256926/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256927/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256927/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2783ac2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256927/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256927/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256927/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3b3f55a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256927/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256927/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256927/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4d7efda --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256927/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256927/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256927/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256927/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256927/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256927/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256927/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256927/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256927/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256927/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256927/test.png b/data/CLs/finished/f1d1/bo5-+/2256927/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256927/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256928/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256928/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9065527 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256928/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256928/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256928/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ab4afdc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256928/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256928/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256928/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..744d030 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256928/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256928/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256928/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256928/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256928/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256928/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256928/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256928/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256928/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256928/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256928/test.png b/data/CLs/finished/f1d1/bo5-+/2256928/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256928/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256929/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256929/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f4c7aad --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256929/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256929/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256929/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..831865f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256929/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256929/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256929/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a36b7aa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256929/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256929/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256929/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256929/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256929/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256929/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256929/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256929/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256929/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256929/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256929/test.png b/data/CLs/finished/f1d1/bo5-+/2256929/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256929/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256930/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256930/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..700961b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256930/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256930/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256930/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..50370c1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256930/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256930/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256930/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..804e192 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256930/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256930/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256930/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256930/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256930/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256930/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256930/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256930/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256930/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256930/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256930/test.png b/data/CLs/finished/f1d1/bo5-+/2256930/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256930/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256931/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256931/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e1bd57f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256931/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256931/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256931/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d5e0181 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256931/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256931/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256931/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3e57b16 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256931/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256931/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256931/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256931/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256931/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256931/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256931/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256931/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256931/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256931/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256931/test.png b/data/CLs/finished/f1d1/bo5-+/2256931/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256931/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256932/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256932/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5ec713a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256932/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256932/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256932/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9f53224 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256932/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256932/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256932/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..aff1a2e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256932/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256932/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256932/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256932/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256932/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256932/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256932/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256932/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256932/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256932/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256932/test.png b/data/CLs/finished/f1d1/bo5-+/2256932/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256932/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256933/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256933/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..93f35c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256933/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256933/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256933/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d27dec0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256933/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256933/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256933/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..de4225a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256933/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256933/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256933/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256933/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256933/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256933/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256933/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256933/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256933/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256933/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256933/test.png b/data/CLs/finished/f1d1/bo5-+/2256933/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256933/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256934/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256934/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e2f64b0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256934/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256934/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256934/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..bd50f31 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256934/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256934/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256934/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f5e7839 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256934/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256934/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256934/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256934/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256934/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256934/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256934/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256934/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256934/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256934/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256934/test.png b/data/CLs/finished/f1d1/bo5-+/2256934/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256934/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256935/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256935/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..718f012 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256935/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256935/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256935/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c486514 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256935/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256935/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256935/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..34749ed --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256935/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256935/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256935/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256935/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256935/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256935/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256935/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256935/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256935/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256935/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256935/test.png b/data/CLs/finished/f1d1/bo5-+/2256935/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256935/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256936/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256936/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..90102b7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256936/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256936/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256936/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..6b8abda --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256936/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256936/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256936/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..710b727 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256936/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256936/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256936/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256936/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256936/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256936/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256936/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256936/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256936/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256936/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256936/test.png b/data/CLs/finished/f1d1/bo5-+/2256936/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256936/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256937/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256937/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5793cb6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256937/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256937/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256937/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b2f1b72 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256937/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256937/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256937/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..dd8e88b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256937/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256937/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256937/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256937/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256937/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256937/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256937/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256937/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256937/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256937/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256937/test.png b/data/CLs/finished/f1d1/bo5-+/2256937/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256937/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256938/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256938/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8459aa1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256938/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256938/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256938/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..23c2fa8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256938/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256938/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256938/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3ba113e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256938/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256938/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256938/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256938/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256938/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256938/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256938/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256938/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256938/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256938/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256938/test.png b/data/CLs/finished/f1d1/bo5-+/2256938/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256938/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256939/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256939/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bde0761 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256939/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256939/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256939/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cf33c2e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256939/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256939/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256939/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..66cbae2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256939/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256939/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256939/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256939/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256939/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256939/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256939/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256939/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256939/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256939/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256939/test.png b/data/CLs/finished/f1d1/bo5-+/2256939/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256939/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256940/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256940/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f4c8039 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256940/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256940/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256940/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0cbbe28 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256940/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256940/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256940/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..43a84ef --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256940/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256940/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256940/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256940/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256940/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256940/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256940/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256940/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256940/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256940/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256940/test.png b/data/CLs/finished/f1d1/bo5-+/2256940/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256940/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256941/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256941/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..87c55cf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256941/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256941/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256941/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..84b64c8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256941/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256941/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256941/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..02909bf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256941/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256941/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256941/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256941/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256941/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256941/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256941/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256941/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256941/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256941/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256941/test.png b/data/CLs/finished/f1d1/bo5-+/2256941/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256941/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256942/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256942/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a843595 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256942/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256942/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256942/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3cb50c1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256942/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256942/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256942/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..efad9ae --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256942/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256942/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256942/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256942/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256942/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256942/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256942/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256942/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256942/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256942/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256942/test.png b/data/CLs/finished/f1d1/bo5-+/2256942/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256942/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256943/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256943/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1898830 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256943/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256943/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256943/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4ab2e6c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256943/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256943/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256943/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0ca22bb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256943/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256943/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256943/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256943/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256943/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256943/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256943/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256943/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256943/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256943/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256943/test.png b/data/CLs/finished/f1d1/bo5-+/2256943/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256943/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256944/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256944/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bd7c5f2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256944/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256944/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256944/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a3c0e25 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256944/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256944/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256944/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..fc29e5c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256944/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256944/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256944/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256944/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256944/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256944/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256944/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256944/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256944/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256944/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256944/test.png b/data/CLs/finished/f1d1/bo5-+/2256944/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256944/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256945/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256945/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1519c7d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256945/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256945/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256945/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9248bbd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256945/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256945/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256945/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3ecd26d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256945/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256945/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256945/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256945/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256945/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256945/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256945/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256945/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256945/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256945/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256945/test.png b/data/CLs/finished/f1d1/bo5-+/2256945/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256945/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256946/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256946/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f01e758 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256946/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256946/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256946/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..31a46de --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256946/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256946/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256946/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f9795c5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256946/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256946/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256946/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256946/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256946/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256946/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256946/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256946/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256946/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256946/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256946/test.png b/data/CLs/finished/f1d1/bo5-+/2256946/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256946/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256947/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256947/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cc56766 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256947/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256947/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256947/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c67f0df --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256947/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256947/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256947/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..af78deb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256947/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256947/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256947/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256947/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256947/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256947/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256947/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256947/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256947/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256947/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256947/test.png b/data/CLs/finished/f1d1/bo5-+/2256947/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256947/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256948/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256948/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5e7f0ca --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256948/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256948/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256948/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c4c0848 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256948/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256948/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256948/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e94ec0f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256948/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256948/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256948/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256948/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256948/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256948/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256948/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256948/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256948/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256948/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256948/test.png b/data/CLs/finished/f1d1/bo5-+/2256948/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256948/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256949/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256949/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c613bed --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256949/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256949/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256949/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5427204 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256949/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256949/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256949/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9c5dae3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256949/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256949/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256949/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256949/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256949/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256949/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256949/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256949/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256949/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256949/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256949/test.png b/data/CLs/finished/f1d1/bo5-+/2256949/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256949/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256950/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256950/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c7dbcd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256950/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256950/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256950/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..30b6a7e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256950/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256950/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256950/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b09dd79 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256950/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256950/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256950/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256950/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256950/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256950/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256950/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256950/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256950/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256950/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256950/test.png b/data/CLs/finished/f1d1/bo5-+/2256950/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256950/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256951/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256951/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..04fb08f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256951/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256951/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256951/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..88bfd0f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256951/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256951/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256951/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..50eadb0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256951/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256951/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256951/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256951/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256951/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256951/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256951/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256951/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256951/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256951/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256951/test.png b/data/CLs/finished/f1d1/bo5-+/2256951/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256951/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256952/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256952/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..06436e0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256952/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256952/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256952/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..69d8532 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256952/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256952/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256952/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..6d2959d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256952/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256952/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256952/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256952/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256952/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256952/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256952/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256952/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256952/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256952/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256952/test.png b/data/CLs/finished/f1d1/bo5-+/2256952/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256952/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256953/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256953/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..894ad9f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256953/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256953/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256953/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..938953c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256953/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256953/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256953/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c6eae65 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256953/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256953/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256953/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256953/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256953/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256953/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256953/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256953/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256953/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256953/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256953/test.png b/data/CLs/finished/f1d1/bo5-+/2256953/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256953/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256954/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256954/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b05c2cc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256954/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256954/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256954/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..10b619c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256954/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256954/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256954/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a482da5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256954/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256954/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256954/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256954/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256954/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256954/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256954/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256954/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256954/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256954/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256954/test.png b/data/CLs/finished/f1d1/bo5-+/2256954/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256954/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256955/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256955/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a9a8220 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256955/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256955/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256955/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..93335e3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256955/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256955/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256955/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f79275d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256955/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256955/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256955/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256955/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256955/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256955/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256955/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256955/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256955/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256955/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256955/test.png b/data/CLs/finished/f1d1/bo5-+/2256955/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256955/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256956/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256956/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..96b7cc8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256956/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256956/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256956/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fb64807 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256956/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256956/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256956/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0ad375d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256956/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256956/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256956/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256956/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256956/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256956/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256956/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256956/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256956/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256956/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256956/test.png b/data/CLs/finished/f1d1/bo5-+/2256956/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256956/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256957/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256957/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..edcb672 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256957/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256957/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256957/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..469992c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256957/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256957/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256957/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f25f561 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256957/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256957/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256957/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256957/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256957/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256957/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256957/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256957/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256957/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256957/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256957/test.png b/data/CLs/finished/f1d1/bo5-+/2256957/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256957/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256958/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256958/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3a3b8aa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256958/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256958/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256958/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..574ce00 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256958/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256958/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256958/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..505044d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256958/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256958/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256958/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256958/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256958/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256958/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256958/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256958/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256958/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256958/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256958/test.png b/data/CLs/finished/f1d1/bo5-+/2256958/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256958/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256959/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256959/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..96f2cf8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256959/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256959/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256959/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d72197b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256959/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256959/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256959/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..13c1d6c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256959/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256959/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256959/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256959/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256959/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256959/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256959/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256959/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256959/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256959/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256959/test.png b/data/CLs/finished/f1d1/bo5-+/2256959/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256959/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256960/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256960/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8130fa5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256960/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256960/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256960/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..51a1d26 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256960/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256960/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256960/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..70471b4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256960/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256960/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256960/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256960/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256960/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256960/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256960/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256960/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256960/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256960/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256960/test.png b/data/CLs/finished/f1d1/bo5-+/2256960/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256960/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256961/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256961/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a3ecc2a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256961/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256961/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256961/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0d81c11 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256961/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256961/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256961/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c98a0e7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256961/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256961/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256961/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256961/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256961/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256961/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256961/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256961/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256961/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256961/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256961/test.png b/data/CLs/finished/f1d1/bo5-+/2256961/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256961/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256962/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256962/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..108fbbc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256962/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256962/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256962/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c049d4b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256962/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256962/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256962/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..fcafda2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256962/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256962/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256962/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256962/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256962/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256962/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256962/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256962/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256962/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256962/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256962/test.png b/data/CLs/finished/f1d1/bo5-+/2256962/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256962/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256963/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256963/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e68f772 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256963/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256963/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256963/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..6f41925 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256963/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256963/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256963/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..1e5bd49 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256963/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256963/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256963/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256963/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256963/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256963/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256963/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256963/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256963/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256963/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256963/test.png b/data/CLs/finished/f1d1/bo5-+/2256963/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256963/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256964/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256964/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0f3ea26 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256964/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256964/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256964/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8df28d7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256964/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256964/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256964/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d492cca --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256964/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256964/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256964/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256964/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256964/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256964/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256964/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256964/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256964/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256964/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256964/test.png b/data/CLs/finished/f1d1/bo5-+/2256964/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256964/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256965/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256965/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..83e7f12 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256965/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256965/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256965/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ddcf3ce --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256965/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256965/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256965/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..95f7771 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256965/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256965/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256965/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256965/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256965/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256965/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256965/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256965/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256965/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256965/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256965/test.png b/data/CLs/finished/f1d1/bo5-+/2256965/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256965/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256966/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256966/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c4fa9b1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256966/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256966/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256966/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9d3416d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256966/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256966/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256966/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d1486ce --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256966/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256966/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256966/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256966/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256966/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256966/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256966/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256966/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256966/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256966/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256966/test.png b/data/CLs/finished/f1d1/bo5-+/2256966/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256966/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256967/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256967/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..044ac53 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256967/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256967/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256967/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8e58c65 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256967/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256967/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256967/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e8bebca --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256967/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256967/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256967/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256967/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256967/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256967/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256967/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256967/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256967/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256967/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256967/test.png b/data/CLs/finished/f1d1/bo5-+/2256967/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256967/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256968/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256968/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ef7afb1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256968/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256968/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256968/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f994b2a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256968/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256968/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256968/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9de975f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256968/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256968/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256968/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256968/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256968/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256968/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256968/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256968/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256968/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256968/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256968/test.png b/data/CLs/finished/f1d1/bo5-+/2256968/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256968/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256969/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256969/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6cb51a1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256969/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256969/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256969/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..adc592b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256969/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256969/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256969/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2a0b3bd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256969/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256969/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256969/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256969/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256969/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256969/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256969/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256969/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256969/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256969/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256969/test.png b/data/CLs/finished/f1d1/bo5-+/2256969/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256969/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256970/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256970/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e1c2e09 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256970/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256970/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256970/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fb164a3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256970/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256970/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256970/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ba86cf3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256970/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256970/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256970/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256970/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256970/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256970/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256970/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256970/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256970/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256970/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256970/test.png b/data/CLs/finished/f1d1/bo5-+/2256970/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256970/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256971/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256971/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..275e8a9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256971/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256971/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256971/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8740d52 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256971/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256971/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256971/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5971ab9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256971/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256971/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256971/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256971/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256971/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256971/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256971/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256971/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256971/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256971/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256971/test.png b/data/CLs/finished/f1d1/bo5-+/2256971/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256971/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256972/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256972/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2dd6ae3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256972/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256972/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256972/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..e1f3653 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256972/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256972/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256972/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ba9fd43 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256972/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256972/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256972/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256972/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256972/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256972/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256972/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256972/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256972/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256972/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256972/test.png b/data/CLs/finished/f1d1/bo5-+/2256972/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256972/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256973/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256973/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6c82cce --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256973/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256973/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256973/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..eb5c440 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256973/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256973/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256973/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0b845b7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256973/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256973/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256973/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256973/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256973/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256973/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256973/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256973/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256973/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256973/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256973/test.png b/data/CLs/finished/f1d1/bo5-+/2256973/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256973/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256974/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256974/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6964d42 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256974/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256974/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256974/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..05d1615 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256974/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256974/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256974/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ffb42c2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256974/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256974/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256974/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256974/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256974/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256974/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256974/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256974/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256974/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256974/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256974/test.png b/data/CLs/finished/f1d1/bo5-+/2256974/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256974/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256975/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256975/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..431226d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256975/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256975/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256975/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5c23410 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256975/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256975/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256975/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..acb3792 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256975/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256975/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256975/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256975/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256975/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256975/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256975/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256975/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256975/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256975/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256975/test.png b/data/CLs/finished/f1d1/bo5-+/2256975/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256975/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256976/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256976/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c26702e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256976/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256976/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256976/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1e87b7c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256976/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256976/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256976/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3763134 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256976/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256976/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256976/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256976/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256976/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256976/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256976/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256976/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256976/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256976/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256976/test.png b/data/CLs/finished/f1d1/bo5-+/2256976/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256976/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256977/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256977/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..132b89b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256977/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256977/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256977/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1adb8f1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256977/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256977/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256977/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ec76c5e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256977/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256977/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256977/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256977/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256977/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256977/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256977/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256977/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256977/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256977/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256977/test.png b/data/CLs/finished/f1d1/bo5-+/2256977/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256977/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256978/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256978/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7bd6600 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256978/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256978/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256978/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..03d2e37 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256978/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256978/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256978/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..30726ac --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256978/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256978/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256978/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256978/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256978/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256978/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256978/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256978/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256978/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256978/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256978/test.png b/data/CLs/finished/f1d1/bo5-+/2256978/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256978/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256979/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256979/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7e056f7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256979/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256979/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256979/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9662dcc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256979/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256979/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256979/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9a950a6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256979/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256979/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256979/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256979/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256979/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256979/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256979/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256979/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256979/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256979/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256979/test.png b/data/CLs/finished/f1d1/bo5-+/2256979/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256979/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256980/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256980/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2d9d18d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256980/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256980/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256980/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d813b16 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256980/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256980/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256980/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..72a5c91 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256980/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256980/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256980/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256980/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256980/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256980/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256980/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256980/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256980/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256980/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256980/test.png b/data/CLs/finished/f1d1/bo5-+/2256980/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256980/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256981/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256981/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a3b3632 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256981/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256981/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256981/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fbc7f14 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256981/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256981/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256981/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..68ac113 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256981/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256981/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256981/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256981/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256981/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256981/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256981/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256981/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256981/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256981/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256981/test.png b/data/CLs/finished/f1d1/bo5-+/2256981/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256981/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256982/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256982/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3c1541a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256982/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256982/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256982/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d281714 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256982/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256982/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256982/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..46bc2b0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256982/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256982/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256982/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256982/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256982/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256982/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256982/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256982/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256982/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256982/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256982/test.png b/data/CLs/finished/f1d1/bo5-+/2256982/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256982/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256983/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256983/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..355af4c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256983/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256983/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256983/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2ee10e1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256983/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256983/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256983/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..560ff70 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256983/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256983/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256983/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256983/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256983/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256983/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256983/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256983/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256983/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256983/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256983/test.png b/data/CLs/finished/f1d1/bo5-+/2256983/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256983/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256984/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256984/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..803c6a9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256984/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256984/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256984/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..408d827 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256984/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256984/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256984/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..896da14 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256984/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256984/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256984/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256984/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256984/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256984/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256984/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256984/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256984/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256984/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256984/test.png b/data/CLs/finished/f1d1/bo5-+/2256984/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256984/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256985/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256985/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b62f2de --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256985/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256985/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256985/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f45ca0f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256985/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256985/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256985/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a5d1e62 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256985/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256985/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256985/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256985/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256985/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256985/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256985/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256985/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256985/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256985/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256985/test.png b/data/CLs/finished/f1d1/bo5-+/2256985/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256985/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256986/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256986/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..80a64c0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256986/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256986/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256986/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..818e25d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256986/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256986/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256986/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d23bf1a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256986/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256986/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256986/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256986/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256986/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256986/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256986/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256986/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256986/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256986/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256986/test.png b/data/CLs/finished/f1d1/bo5-+/2256986/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256986/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256987/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256987/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..30833b4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256987/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256987/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256987/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..e348ed3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256987/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256987/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256987/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..bf8ba2c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256987/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256987/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256987/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256987/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256987/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256987/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256987/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256987/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256987/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256987/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256987/test.png b/data/CLs/finished/f1d1/bo5-+/2256987/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256987/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256988/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256988/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..abc6f69 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256988/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256988/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256988/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..e81cb04 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256988/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256988/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256988/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8e8f4a9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256988/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256988/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256988/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256988/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256988/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256988/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256988/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256988/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256988/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256988/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256988/test.png b/data/CLs/finished/f1d1/bo5-+/2256988/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256988/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256989/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256989/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7d92a42 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256989/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256989/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256989/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c0158ff --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256989/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256989/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256989/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9a9fdc2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256989/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256989/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256989/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256989/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256989/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256989/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256989/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256989/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256989/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256989/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256989/test.png b/data/CLs/finished/f1d1/bo5-+/2256989/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256989/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256990/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256990/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9dd89e7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256990/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256990/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256990/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2af4f23 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256990/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256990/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256990/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0b78654 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256990/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256990/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256990/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256990/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256990/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256990/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256990/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256990/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256990/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256990/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256990/test.png b/data/CLs/finished/f1d1/bo5-+/2256990/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256990/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256991/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256991/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a8284e0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256991/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256991/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256991/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0f425e5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256991/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256991/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256991/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f4b72c8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256991/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256991/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256991/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256991/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256991/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256991/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256991/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256991/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256991/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256991/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256991/test.png b/data/CLs/finished/f1d1/bo5-+/2256991/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256991/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256992/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256992/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0f02fb9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256992/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256992/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256992/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..e75a0ef --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256992/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256992/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256992/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a3332b9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256992/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256992/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256992/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256992/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256992/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256992/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256992/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256992/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256992/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256992/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256992/test.png b/data/CLs/finished/f1d1/bo5-+/2256992/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256992/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256993/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256993/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0a37e72 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256993/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256993/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256993/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4c6db01 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256993/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256993/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256993/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..775d3ff --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256993/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256993/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256993/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256993/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256993/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256993/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256993/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256993/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256993/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256993/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256993/test.png b/data/CLs/finished/f1d1/bo5-+/2256993/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256993/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256994/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256994/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..267d0be --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256994/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256994/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256994/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..36b1171 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256994/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256994/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256994/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..548dbf3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256994/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256994/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256994/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256994/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256994/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256994/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256994/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256994/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256994/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256994/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256994/test.png b/data/CLs/finished/f1d1/bo5-+/2256994/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256994/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256995/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256995/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1e66d40 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256995/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256995/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256995/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4bd2319 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256995/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256995/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256995/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f248a1b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256995/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256995/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256995/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256995/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256995/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256995/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256995/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256995/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256995/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256995/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256995/test.png b/data/CLs/finished/f1d1/bo5-+/2256995/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256995/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256996/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256996/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e3690af --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256996/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256996/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256996/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..35f2d76 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256996/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256996/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256996/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b60962f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256996/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256996/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256996/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256996/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256996/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256996/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256996/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256996/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256996/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256996/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256996/test.png b/data/CLs/finished/f1d1/bo5-+/2256996/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256996/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256997/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256997/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cebded4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256997/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256997/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256997/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..13c9abf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256997/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256997/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256997/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c7a13d5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256997/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256997/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256997/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256997/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256997/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256997/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256997/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256997/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256997/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256997/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256997/test.png b/data/CLs/finished/f1d1/bo5-+/2256997/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256997/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256998/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256998/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f5fd528 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256998/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256998/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256998/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8d400ec --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256998/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256998/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256998/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..95e9e02 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256998/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256998/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256998/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256998/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256998/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256998/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256998/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256998/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256998/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256998/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256998/test.png b/data/CLs/finished/f1d1/bo5-+/2256998/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256998/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256999/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256999/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b0722bb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256999/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256999/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2256999/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f58157c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256999/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256999/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2256999/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..03ed78c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256999/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2256999/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2256999/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256999/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2256999/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2256999/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256999/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2256999/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2256999/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256999/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2256999/test.png b/data/CLs/finished/f1d1/bo5-+/2256999/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2256999/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257000/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257000/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..be2e546 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257000/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257000/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257000/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9455a48 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257000/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257000/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257000/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..264c39b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257000/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257000/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257000/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257000/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257000/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257000/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257000/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257000/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257000/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257000/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257000/test.png b/data/CLs/finished/f1d1/bo5-+/2257000/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257000/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257001/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257001/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1a06150 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257001/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257001/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257001/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..097c10b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257001/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257001/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257001/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..de9b097 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257001/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257001/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257001/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257001/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257001/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257001/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257001/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257001/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257001/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257001/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257001/test.png b/data/CLs/finished/f1d1/bo5-+/2257001/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257001/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257002/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257002/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..da14775 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257002/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257002/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257002/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fafc8c1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257002/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257002/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257002/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b654547 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257002/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257002/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257002/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257002/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257002/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257002/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257002/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257002/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257002/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257002/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257002/test.png b/data/CLs/finished/f1d1/bo5-+/2257002/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257002/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257003/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257003/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f3d7fba --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257003/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257003/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257003/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ecb431d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257003/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257003/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257003/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3a1f6bc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257003/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257003/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257003/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257003/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257003/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257003/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257003/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257003/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257003/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257003/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257003/test.png b/data/CLs/finished/f1d1/bo5-+/2257003/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257003/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257004/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257004/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6662289 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257004/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257004/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257004/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..63a361b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257004/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257004/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257004/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5ee2e45 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257004/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257004/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257004/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257004/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257004/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257004/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257004/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257004/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257004/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257004/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257004/test.png b/data/CLs/finished/f1d1/bo5-+/2257004/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257004/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257005/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257005/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f5e0682 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257005/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257005/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257005/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f183683 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257005/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257005/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257005/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2f2b56c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257005/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257005/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257005/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257005/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257005/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257005/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257005/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257005/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257005/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257005/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257005/test.png b/data/CLs/finished/f1d1/bo5-+/2257005/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257005/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257006/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257006/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c5b457f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257006/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257006/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257006/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4206a65 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257006/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257006/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257006/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..331a2ba --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257006/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257006/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257006/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257006/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257006/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257006/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257006/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257006/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257006/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257006/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257006/test.png b/data/CLs/finished/f1d1/bo5-+/2257006/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257006/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257007/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257007/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..28d6318 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257007/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257007/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257007/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1cff7ed --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257007/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257007/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257007/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e9d2296 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257007/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257007/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257007/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257007/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257007/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257007/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257007/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257007/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257007/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257007/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257007/test.png b/data/CLs/finished/f1d1/bo5-+/2257007/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257007/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257008/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257008/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4b1fbb1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257008/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257008/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257008/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c13d550 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257008/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257008/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257008/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..22fe30a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257008/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257008/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257008/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257008/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257008/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257008/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257008/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257008/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257008/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257008/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257008/test.png b/data/CLs/finished/f1d1/bo5-+/2257008/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257008/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257009/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257009/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2d9c380 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257009/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257009/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257009/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c67ce09 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257009/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257009/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257009/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..783a714 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257009/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257009/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257009/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257009/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257009/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257009/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257009/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257009/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257009/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257009/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257009/test.png b/data/CLs/finished/f1d1/bo5-+/2257009/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257009/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257010/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257010/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..507081d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257010/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257010/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257010/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1f1259f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257010/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257010/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257010/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..bfec523 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257010/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257010/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257010/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257010/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257010/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257010/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257010/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257010/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257010/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257010/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257010/test.png b/data/CLs/finished/f1d1/bo5-+/2257010/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257010/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257011/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257011/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7be8280 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257011/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257011/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257011/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ce2485f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257011/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257011/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257011/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d90ae33 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257011/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257011/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257011/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257011/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257011/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257011/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257011/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257011/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257011/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257011/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257011/test.png b/data/CLs/finished/f1d1/bo5-+/2257011/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257011/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257012/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257012/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..f0c4225 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257012/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257012/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257012/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ef74f66 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257012/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257012/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257012/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3c9fd7f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257012/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257012/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257012/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257012/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257012/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257012/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257012/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257012/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257012/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257012/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257012/test.png b/data/CLs/finished/f1d1/bo5-+/2257012/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257012/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257013/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257013/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b0efa42 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257013/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257013/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257013/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..41d67d1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257013/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257013/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257013/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..aa2aada --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257013/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257013/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257013/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257013/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257013/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257013/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257013/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257013/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257013/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257013/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257013/test.png b/data/CLs/finished/f1d1/bo5-+/2257013/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257013/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257014/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257014/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..27e2153 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257014/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257014/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257014/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..782f4f1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257014/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257014/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257014/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..fa5ec10 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257014/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257014/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257014/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257014/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257014/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257014/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257014/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257014/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257014/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257014/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257014/test.png b/data/CLs/finished/f1d1/bo5-+/2257014/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257014/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257015/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257015/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..11e3baf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257015/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257015/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257015/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5572969 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257015/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257015/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257015/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d6071d8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257015/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257015/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257015/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257015/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257015/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257015/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257015/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257015/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257015/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257015/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257015/test.png b/data/CLs/finished/f1d1/bo5-+/2257015/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257015/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257016/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257016/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b3929f8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257016/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257016/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257016/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cfacc99 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257016/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257016/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257016/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a6afc54 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257016/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257016/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257016/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257016/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257016/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257016/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257016/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257016/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257016/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257016/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257016/test.png b/data/CLs/finished/f1d1/bo5-+/2257016/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257016/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257017/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257017/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3f29e5c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257017/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257017/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257017/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..18d1dc5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257017/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257017/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257017/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8b78cf6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257017/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257017/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257017/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257017/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257017/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257017/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257017/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257017/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257017/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257017/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257017/test.png b/data/CLs/finished/f1d1/bo5-+/2257017/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257017/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257018/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257018/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0fd1bfd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257018/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257018/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257018/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fb36dfd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257018/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257018/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257018/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f0aef92 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257018/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257018/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257018/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257018/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257018/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257018/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257018/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257018/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257018/raremodel-nb1.py new file mode 100644 index 0000000..7e46ea6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257018/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-1.5, upper_limit=1.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257018/test.png b/data/CLs/finished/f1d1/bo5-+/2257018/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257018/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257037/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257037/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3c0a9b7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257037/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257037/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257037/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..de92f0f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257037/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257037/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257037/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8b414d0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257037/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257037/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257037/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257037/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257037/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257037/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257037/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257037/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257037/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257037/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257037/test.png b/data/CLs/finished/f1d1/bo5-+/2257037/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257037/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257038/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257038/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2838d39 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257038/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257038/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257038/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..81d9142 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257038/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257038/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257038/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5e35aee --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257038/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257038/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257038/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257038/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257038/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257038/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257038/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257038/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257038/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257038/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257038/test.png b/data/CLs/finished/f1d1/bo5-+/2257038/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257038/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257039/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257039/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..781f984 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257039/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257039/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257039/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2963593 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257039/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257039/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257039/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..cfcd7fe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257039/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257039/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257039/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257039/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257039/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257039/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257039/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257039/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257039/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257039/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257039/test.png b/data/CLs/finished/f1d1/bo5-+/2257039/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257039/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257040/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257040/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6eed648 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257040/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257040/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257040/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d837e27 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257040/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257040/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257040/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..092c8f3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257040/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257040/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257040/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257040/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257040/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257040/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257040/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257040/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257040/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257040/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257040/test.png b/data/CLs/finished/f1d1/bo5-+/2257040/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257040/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257041/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257041/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b6dc83e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257041/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257041/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257041/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d3327f9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257041/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257041/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257041/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..38addfa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257041/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257041/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257041/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257041/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257041/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257041/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257041/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257041/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257041/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257041/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257041/test.png b/data/CLs/finished/f1d1/bo5-+/2257041/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257041/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257042/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257042/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7fead2a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257042/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257042/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257042/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ff55198 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257042/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257042/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257042/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..01aa8b2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257042/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257042/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257042/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257042/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257042/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257042/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257042/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257042/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257042/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257042/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257042/test.png b/data/CLs/finished/f1d1/bo5-+/2257042/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257042/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257043/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257043/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2a0103b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257043/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257043/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257043/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4b4732b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257043/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257043/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257043/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..233bf3e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257043/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257043/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257043/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257043/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257043/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257043/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257043/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257043/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257043/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257043/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257043/test.png b/data/CLs/finished/f1d1/bo5-+/2257043/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257043/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257044/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257044/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3ce031b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257044/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257044/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257044/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ca0789c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257044/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257044/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257044/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ed0afa7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257044/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257044/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257044/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257044/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257044/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257044/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257044/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257044/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257044/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257044/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257044/test.png b/data/CLs/finished/f1d1/bo5-+/2257044/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257044/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257045/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257045/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..81779e6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257045/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257045/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257045/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2af2bea --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257045/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257045/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257045/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5425bf4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257045/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257045/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257045/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257045/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257045/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257045/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257045/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257045/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257045/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257045/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257045/test.png b/data/CLs/finished/f1d1/bo5-+/2257045/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257045/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257046/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257046/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..663d559 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257046/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257046/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257046/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2d12d1f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257046/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257046/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257046/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..bc05d72 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257046/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257046/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257046/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257046/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257046/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257046/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257046/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257046/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257046/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257046/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257046/test.png b/data/CLs/finished/f1d1/bo5-+/2257046/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257046/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257047/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257047/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..469953b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257047/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257047/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257047/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b465ed0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257047/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257047/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257047/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0fa471d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257047/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257047/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257047/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257047/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257047/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257047/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257047/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257047/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257047/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257047/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257047/test.png b/data/CLs/finished/f1d1/bo5-+/2257047/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257047/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257048/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257048/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a8d34fe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257048/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257048/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257048/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..656722d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257048/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257048/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257048/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c5796f0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257048/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257048/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257048/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257048/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257048/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257048/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257048/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257048/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257048/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257048/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257048/test.png b/data/CLs/finished/f1d1/bo5-+/2257048/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257048/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257049/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257049/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1fbae4c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257049/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257049/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257049/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1e15322 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257049/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257049/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257049/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0b14c5b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257049/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257049/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257049/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257049/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257049/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257049/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257049/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257049/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257049/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257049/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257049/test.png b/data/CLs/finished/f1d1/bo5-+/2257049/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257049/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257050/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257050/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..13b26c8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257050/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257050/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257050/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7769380 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257050/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257050/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257050/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..27b0ce8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257050/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257050/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257050/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257050/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257050/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257050/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257050/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257050/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257050/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257050/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257050/test.png b/data/CLs/finished/f1d1/bo5-+/2257050/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257050/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257051/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257051/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..33b920f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257051/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257051/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257051/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7ec112c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257051/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257051/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257051/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..912e057 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257051/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257051/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257051/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257051/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257051/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257051/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257051/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257051/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257051/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257051/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257051/test.png b/data/CLs/finished/f1d1/bo5-+/2257051/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257051/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257052/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257052/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..221e5d5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257052/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257052/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257052/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fcc9536 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257052/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257052/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257052/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7b55c7d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257052/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257052/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257052/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257052/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257052/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257052/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257052/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257052/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257052/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257052/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257052/test.png b/data/CLs/finished/f1d1/bo5-+/2257052/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257052/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257053/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257053/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a620cb2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257053/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257053/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257053/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2ccc2da --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257053/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257053/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257053/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c03e2fe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257053/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257053/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257053/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257053/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257053/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257053/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257053/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257053/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257053/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257053/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257053/test.png b/data/CLs/finished/f1d1/bo5-+/2257053/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257053/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257054/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257054/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9ac3d40 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257054/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257054/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257054/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..47a220a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257054/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257054/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257054/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e460353 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257054/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257054/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257054/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257054/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257054/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257054/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257054/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257054/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257054/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257054/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257054/test.png b/data/CLs/finished/f1d1/bo5-+/2257054/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257054/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257055/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257055/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..69e4b3e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257055/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257055/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257055/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..884038f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257055/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257055/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257055/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257055/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257055/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257055/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257055/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257055/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257055/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257055/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257055/test.png b/data/CLs/finished/f1d1/bo5-+/2257055/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257055/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257056/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257056/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..be99586 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257056/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257056/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257056/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..03c318f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257056/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257056/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257056/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9a8d565 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257056/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257056/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257056/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257056/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257056/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257056/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257056/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257056/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257056/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257056/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257056/test.png b/data/CLs/finished/f1d1/bo5-+/2257056/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257056/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257057/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257057/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..071889c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257057/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257057/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257057/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..397276a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257057/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257057/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257057/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c6148f9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257057/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257057/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257057/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257057/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257057/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257057/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257057/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257057/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257057/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257057/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257057/test.png b/data/CLs/finished/f1d1/bo5-+/2257057/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257057/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257058/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257058/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..89ed748 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257058/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257058/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257058/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..e82d096 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257058/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257058/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257058/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f7bc8af --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257058/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257058/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257058/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257058/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257058/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257058/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257058/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257058/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257058/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257058/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257058/test.png b/data/CLs/finished/f1d1/bo5-+/2257058/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257058/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257059/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257059/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..09cae47 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257059/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257059/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257059/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2fbcb0b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257059/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257059/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257059/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..75aecdb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257059/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257059/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257059/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257059/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257059/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257059/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257059/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257059/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257059/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257059/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257059/test.png b/data/CLs/finished/f1d1/bo5-+/2257059/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257059/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257060/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257060/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7beea4d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257060/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257060/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257060/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..41b062f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257060/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257060/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257060/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ab6a2f5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257060/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257060/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257060/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257060/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257060/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257060/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257060/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257060/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257060/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257060/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257060/test.png b/data/CLs/finished/f1d1/bo5-+/2257060/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257060/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257061/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257061/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1ea2ade --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257061/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257061/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257061/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ca920bf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257061/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257061/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257061/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..deebfa5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257061/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257061/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257061/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257061/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257061/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257061/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257061/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257061/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257061/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257061/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257061/test.png b/data/CLs/finished/f1d1/bo5-+/2257061/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257061/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257062/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257062/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a20e1cd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257062/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257062/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257062/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f17ba56 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257062/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257062/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257062/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..75b506b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257062/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257062/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257062/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257062/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257062/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257062/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257062/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257062/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257062/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257062/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257062/test.png b/data/CLs/finished/f1d1/bo5-+/2257062/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257062/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257063/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257063/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ecee5e2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257063/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257063/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257063/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d3f1ffb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257063/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257063/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257063/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8699087 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257063/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257063/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257063/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257063/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257063/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257063/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257063/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257063/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257063/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257063/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257063/test.png b/data/CLs/finished/f1d1/bo5-+/2257063/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257063/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257064/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257064/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9756d01 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257064/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257064/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257064/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8bc0dac --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257064/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257064/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257064/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..aa1b75e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257064/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257064/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257064/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257064/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257064/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257064/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257064/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257064/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257064/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257064/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257064/test.png b/data/CLs/finished/f1d1/bo5-+/2257064/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257064/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257065/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257065/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c2ea119 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257065/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257065/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257065/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d1f18cf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257065/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257065/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257065/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7f85bab --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257065/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257065/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257065/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257065/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257065/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257065/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257065/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257065/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257065/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257065/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257065/test.png b/data/CLs/finished/f1d1/bo5-+/2257065/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257065/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257066/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257066/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..71819e0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257066/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257066/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257066/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2e34b6f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257066/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257066/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257066/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..53bfdd0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257066/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257066/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257066/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257066/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257066/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257066/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257066/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257066/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257066/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257066/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257066/test.png b/data/CLs/finished/f1d1/bo5-+/2257066/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257066/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257067/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257067/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3e7b6c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257067/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257067/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257067/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2427516 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257067/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257067/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257067/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f3440b9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257067/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257067/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257067/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257067/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257067/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257067/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257067/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257067/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257067/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257067/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257067/test.png b/data/CLs/finished/f1d1/bo5-+/2257067/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257067/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257068/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257068/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..856a48b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257068/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257068/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257068/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c4fa094 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257068/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257068/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257068/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..cdd6c53 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257068/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257068/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257068/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257068/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257068/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257068/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257068/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257068/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257068/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257068/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257068/test.png b/data/CLs/finished/f1d1/bo5-+/2257068/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257068/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257069/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257069/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..faf3376 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257069/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257069/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257069/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1857121 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257069/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257069/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257069/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..471e3a6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257069/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257069/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257069/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257069/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257069/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257069/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257069/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257069/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257069/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257069/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257069/test.png b/data/CLs/finished/f1d1/bo5-+/2257069/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257069/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257070/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257070/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..233d986 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257070/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257070/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257070/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1af4d69 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257070/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257070/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257070/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ed7c3fc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257070/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257070/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257070/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257070/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257070/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257070/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257070/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257070/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257070/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257070/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257070/test.png b/data/CLs/finished/f1d1/bo5-+/2257070/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257070/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257071/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257071/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7e34497 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257071/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257071/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257071/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..6ef3fdf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257071/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257071/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257071/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..132f6f9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257071/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257071/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257071/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257071/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257071/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257071/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257071/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257071/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257071/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257071/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257071/test.png b/data/CLs/finished/f1d1/bo5-+/2257071/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257071/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257072/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257072/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0ee201e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257072/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257072/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257072/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5729360 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257072/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257072/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257072/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..12a285e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257072/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257072/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257072/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257072/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257072/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257072/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257072/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257072/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257072/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257072/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257072/test.png b/data/CLs/finished/f1d1/bo5-+/2257072/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257072/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257073/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257073/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7c7b374 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257073/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257073/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257073/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0f6f5d4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257073/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257073/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257073/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8c186e6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257073/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257073/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257073/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257073/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257073/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257073/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257073/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257073/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257073/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257073/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257073/test.png b/data/CLs/finished/f1d1/bo5-+/2257073/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257073/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257074/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257074/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4189745 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257074/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257074/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257074/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..63bda4a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257074/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257074/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257074/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7d465f1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257074/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257074/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257074/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257074/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257074/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257074/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257074/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257074/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257074/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257074/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257074/test.png b/data/CLs/finished/f1d1/bo5-+/2257074/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257074/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257075/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257075/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..08e07c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257075/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257075/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257075/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..e8fe8e0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257075/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257075/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257075/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7adc15b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257075/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257075/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257075/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257075/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257075/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257075/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257075/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257075/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257075/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257075/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257075/test.png b/data/CLs/finished/f1d1/bo5-+/2257075/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257075/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257076/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257076/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ad4f1ec --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257076/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257076/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257076/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b0e3a82 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257076/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257076/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257076/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..1a8a35d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257076/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257076/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257076/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257076/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257076/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257076/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257076/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257076/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257076/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257076/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257076/test.png b/data/CLs/finished/f1d1/bo5-+/2257076/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257076/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257077/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257077/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0dbd189 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257077/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257077/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257077/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cf98d4a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257077/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257077/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257077/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..eee93e6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257077/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257077/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257077/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257077/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257077/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257077/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257077/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257077/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257077/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257077/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257077/test.png b/data/CLs/finished/f1d1/bo5-+/2257077/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257077/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257078/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257078/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8fc224e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257078/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257078/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257078/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ca61f47 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257078/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257078/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257078/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d2f2ba7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257078/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257078/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257078/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257078/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257078/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257078/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257078/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257078/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257078/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257078/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257078/test.png b/data/CLs/finished/f1d1/bo5-+/2257078/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257078/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257079/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257079/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fba7229 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257079/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257079/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257079/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2ab4c83 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257079/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257079/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257079/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..599841e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257079/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257079/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257079/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257079/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257079/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257079/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257079/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257079/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257079/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257079/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257079/test.png b/data/CLs/finished/f1d1/bo5-+/2257079/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257079/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257080/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257080/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1210ff3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257080/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257080/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257080/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b8e0b34 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257080/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257080/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257080/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2c97da4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257080/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257080/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257080/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257080/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257080/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257080/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257080/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257080/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257080/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257080/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257080/test.png b/data/CLs/finished/f1d1/bo5-+/2257080/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257080/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257081/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257081/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c966da5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257081/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257081/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257081/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c078443 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257081/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257081/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257081/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d1e4a1b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257081/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257081/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257081/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257081/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257081/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257081/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257081/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257081/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257081/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257081/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257081/test.png b/data/CLs/finished/f1d1/bo5-+/2257081/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257081/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257082/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257082/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c2ab23e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257082/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257082/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257082/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cc54e27 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257082/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257082/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257082/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0637ca6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257082/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257082/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257082/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257082/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257082/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257082/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257082/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257082/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257082/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257082/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257082/test.png b/data/CLs/finished/f1d1/bo5-+/2257082/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257082/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257083/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257083/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7c51cd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257083/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257083/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257083/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0bc5b8f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257083/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257083/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257083/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..345cdcb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257083/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257083/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257083/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257083/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257083/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257083/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257083/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257083/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257083/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257083/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257083/test.png b/data/CLs/finished/f1d1/bo5-+/2257083/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257083/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257084/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257084/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..961843a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257084/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257084/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257084/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..560fcf8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257084/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257084/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257084/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..304bc7c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257084/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257084/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257084/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257084/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257084/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257084/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257084/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257084/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257084/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257084/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257084/test.png b/data/CLs/finished/f1d1/bo5-+/2257084/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257084/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257085/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257085/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..06001fc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257085/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257085/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257085/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4e76f0d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257085/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257085/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257085/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8a8142e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257085/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257085/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257085/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257085/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257085/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257085/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257085/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257085/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257085/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257085/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257085/test.png b/data/CLs/finished/f1d1/bo5-+/2257085/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257085/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257086/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257086/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..58f11e7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257086/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257086/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257086/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c60958a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257086/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257086/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257086/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..029f5c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257086/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257086/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257086/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257086/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257086/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257086/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257086/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257086/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257086/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257086/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257086/test.png b/data/CLs/finished/f1d1/bo5-+/2257086/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257086/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257087/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257087/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..771b9aa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257087/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257087/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257087/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a46091b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257087/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257087/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257087/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..32f92a6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257087/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257087/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257087/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257087/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257087/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257087/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257087/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257087/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257087/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257087/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257087/test.png b/data/CLs/finished/f1d1/bo5-+/2257087/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257087/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257088/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257088/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..79047c9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257088/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257088/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257088/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3c8b4be --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257088/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257088/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257088/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b93ff4f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257088/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257088/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257088/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257088/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257088/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257088/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257088/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257088/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257088/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257088/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257088/test.png b/data/CLs/finished/f1d1/bo5-+/2257088/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257088/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257089/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257089/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0918620 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257089/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257089/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257089/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0e9f45c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257089/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257089/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257089/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4a1e3e9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257089/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257089/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257089/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257089/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257089/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257089/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257089/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257089/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257089/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257089/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257089/test.png b/data/CLs/finished/f1d1/bo5-+/2257089/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257089/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257090/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257090/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bd4d884 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257090/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257090/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257090/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..e02be03 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257090/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257090/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257090/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c129ccb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257090/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257090/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257090/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257090/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257090/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257090/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257090/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257090/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257090/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257090/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257090/test.png b/data/CLs/finished/f1d1/bo5-+/2257090/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257090/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257091/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257091/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3a4cfee --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257091/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257091/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257091/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2e8f5c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257091/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257091/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257091/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0d4de59 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257091/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257091/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257091/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257091/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257091/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257091/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257091/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257091/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257091/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257091/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257091/test.png b/data/CLs/finished/f1d1/bo5-+/2257091/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257091/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257092/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257092/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1ff3be9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257092/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257092/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257092/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0b6ed36 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257092/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257092/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257092/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f04e05c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257092/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257092/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257092/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257092/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257092/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257092/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257092/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257092/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257092/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257092/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257092/test.png b/data/CLs/finished/f1d1/bo5-+/2257092/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257092/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257093/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257093/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e155166 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257093/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257093/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257093/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ed8545b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257093/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257093/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257093/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..27caca6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257093/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257093/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257093/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257093/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257093/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257093/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257093/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257093/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257093/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257093/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257093/test.png b/data/CLs/finished/f1d1/bo5-+/2257093/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257093/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257094/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257094/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3f6aba8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257094/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257094/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257094/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..305b398 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257094/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257094/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257094/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..42b70fb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257094/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257094/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257094/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257094/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257094/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257094/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257094/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257094/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257094/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257094/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257094/test.png b/data/CLs/finished/f1d1/bo5-+/2257094/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257094/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257095/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257095/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3034ac2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257095/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257095/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257095/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d38602d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257095/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257095/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257095/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..15d5670 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257095/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257095/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257095/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257095/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257095/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257095/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257095/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257095/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257095/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257095/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257095/test.png b/data/CLs/finished/f1d1/bo5-+/2257095/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257095/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257096/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257096/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b29b037 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257096/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257096/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257096/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3bd96d8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257096/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257096/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257096/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..1db8523 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257096/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257096/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257096/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257096/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257096/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257096/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257096/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257096/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257096/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257096/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257096/test.png b/data/CLs/finished/f1d1/bo5-+/2257096/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257096/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257097/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257097/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4fd9365 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257097/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257097/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257097/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c05a4fe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257097/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257097/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257097/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..aaf5a77 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257097/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257097/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257097/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257097/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257097/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257097/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257097/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257097/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257097/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257097/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257097/test.png b/data/CLs/finished/f1d1/bo5-+/2257097/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257097/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257098/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257098/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..86dfecf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257098/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257098/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257098/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2ae2cfe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257098/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257098/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257098/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..95d6f56 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257098/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257098/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257098/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257098/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257098/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257098/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257098/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257098/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257098/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257098/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257098/test.png b/data/CLs/finished/f1d1/bo5-+/2257098/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257098/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257099/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257099/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ba1ee28 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257099/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257099/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257099/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ac74121 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257099/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257099/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257099/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..cbbd7cd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257099/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257099/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257099/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257099/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257099/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257099/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257099/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257099/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257099/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257099/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257099/test.png b/data/CLs/finished/f1d1/bo5-+/2257099/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257099/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257100/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257100/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9dfd14b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257100/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257100/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257100/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f8ec832 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257100/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257100/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257100/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b16906c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257100/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257100/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257100/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257100/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257100/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257100/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257100/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257100/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257100/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257100/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257100/test.png b/data/CLs/finished/f1d1/bo5-+/2257100/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257100/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257101/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257101/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4e50bb9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257101/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257101/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257101/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..13128d1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257101/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257101/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257101/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..621c426 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257101/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257101/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257101/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257101/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257101/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257101/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257101/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257101/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257101/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257101/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257101/test.png b/data/CLs/finished/f1d1/bo5-+/2257101/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257101/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257102/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257102/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bf454e7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257102/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257102/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257102/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a2ba4ba --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257102/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257102/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257102/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a2ab7cb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257102/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257102/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257102/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257102/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257102/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257102/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257102/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257102/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257102/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257102/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257102/test.png b/data/CLs/finished/f1d1/bo5-+/2257102/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257102/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257103/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257103/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..837f5c3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257103/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257103/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257103/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3b54aa2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257103/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257103/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257103/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d767e64 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257103/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257103/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257103/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257103/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257103/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257103/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257103/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257103/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257103/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257103/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257103/test.png b/data/CLs/finished/f1d1/bo5-+/2257103/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257103/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257104/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257104/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..55d4f33 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257104/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257104/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257104/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3345838 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257104/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257104/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257104/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f027c71 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257104/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257104/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257104/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257104/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257104/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257104/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257104/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257104/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257104/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257104/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257104/test.png b/data/CLs/finished/f1d1/bo5-+/2257104/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257104/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257105/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257105/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..689fd02 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257105/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257105/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257105/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..592459f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257105/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257105/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257105/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3273749 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257105/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257105/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257105/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257105/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257105/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257105/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257105/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257105/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257105/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257105/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257105/test.png b/data/CLs/finished/f1d1/bo5-+/2257105/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257105/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257106/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257106/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..687609e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257106/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257106/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257106/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2c03097 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257106/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257106/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257106/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..18e2c7f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257106/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257106/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257106/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257106/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257106/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257106/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257106/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257106/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257106/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257106/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257106/test.png b/data/CLs/finished/f1d1/bo5-+/2257106/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257106/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257107/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257107/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..19a2b84 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257107/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257107/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257107/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..158dadf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257107/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257107/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257107/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9600912 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257107/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257107/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257107/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257107/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257107/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257107/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257107/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257107/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257107/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257107/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257107/test.png b/data/CLs/finished/f1d1/bo5-+/2257107/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257107/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257108/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257108/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2a5ba3a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257108/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257108/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257108/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ac21fc9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257108/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257108/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257108/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..85655bd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257108/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257108/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257108/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257108/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257108/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257108/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257108/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257108/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257108/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257108/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257108/test.png b/data/CLs/finished/f1d1/bo5-+/2257108/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257108/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257109/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257109/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..407d9f3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257109/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257109/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257109/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d264711 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257109/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257109/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257109/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e971f81 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257109/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257109/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257109/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257109/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257109/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257109/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257109/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257109/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257109/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257109/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257109/test.png b/data/CLs/finished/f1d1/bo5-+/2257109/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257109/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257110/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257110/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3c59672 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257110/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257110/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257110/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..96d4495 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257110/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257110/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257110/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..bbd590d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257110/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257110/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257110/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257110/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257110/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257110/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257110/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257110/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257110/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257110/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257110/test.png b/data/CLs/finished/f1d1/bo5-+/2257110/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257110/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257111/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257111/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..00f96b7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257111/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257111/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257111/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c3d9bf8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257111/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257111/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257111/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5743819 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257111/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257111/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257111/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257111/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257111/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257111/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257111/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257111/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257111/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257111/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257111/test.png b/data/CLs/finished/f1d1/bo5-+/2257111/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257111/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257112/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257112/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7df8c1a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257112/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257112/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257112/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..17bff0d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257112/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257112/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257112/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f85e13b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257112/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257112/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257112/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257112/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257112/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257112/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257112/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257112/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257112/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257112/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257112/test.png b/data/CLs/finished/f1d1/bo5-+/2257112/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257112/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257113/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257113/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b465ed5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257113/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257113/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257113/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..780d51d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257113/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257113/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257113/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a26e24c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257113/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257113/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257113/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257113/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257113/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257113/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257113/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257113/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257113/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257113/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257113/test.png b/data/CLs/finished/f1d1/bo5-+/2257113/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257113/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257114/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257114/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a5051cf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257114/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257114/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257114/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..481d50f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257114/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257114/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257114/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7e892ff --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257114/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257114/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257114/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257114/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257114/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257114/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257114/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257114/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257114/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257114/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257114/test.png b/data/CLs/finished/f1d1/bo5-+/2257114/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257114/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257115/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257115/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..49db3ae --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257115/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257115/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257115/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8b54750 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257115/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257115/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257115/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..aadc3e8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257115/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257115/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257115/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257115/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257115/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257115/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257115/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257115/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257115/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257115/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257115/test.png b/data/CLs/finished/f1d1/bo5-+/2257115/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257115/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257116/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257116/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..571be4c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257116/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257116/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257116/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8747c9a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257116/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257116/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257116/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..513fcc1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257116/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257116/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257116/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257116/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257116/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257116/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257116/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257116/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257116/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257116/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257116/test.png b/data/CLs/finished/f1d1/bo5-+/2257116/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257116/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257117/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257117/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..163ee42 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257117/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257117/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257117/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..dac7f53 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257117/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257117/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257117/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f9357bc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257117/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257117/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257117/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257117/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257117/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257117/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257117/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257117/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257117/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257117/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257117/test.png b/data/CLs/finished/f1d1/bo5-+/2257117/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257117/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257118/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257118/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..96b0e76 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257118/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257118/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257118/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..25062e6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257118/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257118/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257118/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b5b52bb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257118/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257118/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257118/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257118/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257118/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257118/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257118/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257118/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257118/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257118/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257118/test.png b/data/CLs/finished/f1d1/bo5-+/2257118/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257118/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257119/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257119/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..87366ae --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257119/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257119/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257119/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2681aa3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257119/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257119/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257119/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..885d6b9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257119/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257119/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257119/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257119/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257119/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257119/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257119/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257119/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257119/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257119/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257119/test.png b/data/CLs/finished/f1d1/bo5-+/2257119/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257119/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257120/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257120/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..fbad887 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257120/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257120/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257120/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..875d9e4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257120/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257120/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257120/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..99713b6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257120/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257120/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257120/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257120/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257120/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257120/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257120/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257120/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257120/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257120/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257120/test.png b/data/CLs/finished/f1d1/bo5-+/2257120/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257120/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257121/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257121/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4d8f18a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257121/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257121/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257121/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..643798a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257121/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257121/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257121/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8b3b99c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257121/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257121/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257121/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257121/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257121/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257121/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257121/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257121/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257121/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257121/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257121/test.png b/data/CLs/finished/f1d1/bo5-+/2257121/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257121/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257122/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257122/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e787281 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257122/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257122/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257122/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..afd92b1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257122/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257122/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257122/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..23eaa34 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257122/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257122/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257122/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257122/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257122/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257122/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257122/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257122/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257122/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257122/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257122/test.png b/data/CLs/finished/f1d1/bo5-+/2257122/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257122/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257123/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257123/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5ca090d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257123/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257123/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257123/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..99779ab --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257123/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257123/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257123/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..babc356 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257123/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257123/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257123/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257123/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257123/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257123/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257123/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257123/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257123/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257123/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257123/test.png b/data/CLs/finished/f1d1/bo5-+/2257123/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257123/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257124/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257124/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7b225cc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257124/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257124/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257124/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..63bea80 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257124/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257124/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257124/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..fda8ad5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257124/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257124/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257124/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257124/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257124/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257124/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257124/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257124/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257124/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257124/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257124/test.png b/data/CLs/finished/f1d1/bo5-+/2257124/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257124/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257125/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257125/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2684258 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257125/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257125/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257125/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2ebe798 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257125/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257125/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257125/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..706f0ad --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257125/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257125/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257125/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257125/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257125/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257125/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257125/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257125/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257125/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257125/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257125/test.png b/data/CLs/finished/f1d1/bo5-+/2257125/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257125/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257126/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257126/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5b7c0fb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257126/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257126/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257126/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f565316 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257126/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257126/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257126/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a17f026 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257126/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257126/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257126/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257126/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257126/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257126/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257126/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257126/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257126/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257126/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257126/test.png b/data/CLs/finished/f1d1/bo5-+/2257126/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257126/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257127/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257127/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..905e263 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257127/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257127/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257127/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2beac1f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257127/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257127/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257127/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..482c04c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257127/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257127/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257127/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257127/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257127/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257127/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257127/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257127/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257127/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257127/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257127/test.png b/data/CLs/finished/f1d1/bo5-+/2257127/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257127/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257128/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257128/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c579383 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257128/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257128/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257128/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a85a9ad --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257128/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257128/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257128/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..dae9f46 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257128/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257128/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257128/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257128/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257128/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257128/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257128/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257128/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257128/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257128/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257128/test.png b/data/CLs/finished/f1d1/bo5-+/2257128/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257128/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257129/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257129/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4a49f77 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257129/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257129/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257129/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..82d2abe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257129/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257129/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257129/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4884357 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257129/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257129/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257129/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257129/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257129/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257129/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257129/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257129/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257129/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257129/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257129/test.png b/data/CLs/finished/f1d1/bo5-+/2257129/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257129/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257130/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257130/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dffc104 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257130/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257130/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257130/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cc50595 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257130/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257130/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257130/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a320bba --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257130/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257130/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257130/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257130/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257130/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257130/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257130/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257130/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257130/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257130/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257130/test.png b/data/CLs/finished/f1d1/bo5-+/2257130/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257130/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257131/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257131/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..48b4b35 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257131/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257131/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257131/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9e775d7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257131/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257131/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257131/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ac337b9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257131/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257131/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257131/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257131/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257131/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257131/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257131/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257131/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257131/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257131/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257131/test.png b/data/CLs/finished/f1d1/bo5-+/2257131/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257131/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257132/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257132/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b371fd0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257132/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257132/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257132/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ee03d12 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257132/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257132/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257132/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..91a1d2b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257132/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257132/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257132/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257132/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257132/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257132/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257132/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257132/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257132/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257132/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257132/test.png b/data/CLs/finished/f1d1/bo5-+/2257132/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257132/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257133/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257133/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8ca3d5e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257133/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257133/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257133/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2114887 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257133/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257133/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257133/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b114556 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257133/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257133/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257133/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257133/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257133/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257133/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257133/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257133/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257133/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257133/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257133/test.png b/data/CLs/finished/f1d1/bo5-+/2257133/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257133/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257134/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257134/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bd6ec0f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257134/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257134/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257134/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9f575e6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257134/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257134/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257134/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d5761e9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257134/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257134/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257134/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257134/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257134/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257134/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257134/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257134/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257134/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257134/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257134/test.png b/data/CLs/finished/f1d1/bo5-+/2257134/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257134/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257135/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257135/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8b65926 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257135/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257135/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257135/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..caf0678 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257135/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257135/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257135/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4d4e4f7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257135/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257135/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257135/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257135/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257135/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257135/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257135/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257135/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257135/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257135/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257135/test.png b/data/CLs/finished/f1d1/bo5-+/2257135/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257135/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257136/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257136/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9b2e16e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257136/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257136/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257136/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f20487c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257136/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257136/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257136/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..440bcc9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257136/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257136/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257136/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257136/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257136/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257136/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257136/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257136/raremodel-nb1.py b/data/CLs/finished/f1d1/bo5-+/2257136/raremodel-nb1.py new file mode 100644 index 0000000..d5aaf94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257136/raremodel-nb1.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ >= 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257136/test.png b/data/CLs/finished/f1d1/bo5-+/2257136/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257136/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257137/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257137/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1057d37 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257137/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257137/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257137/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..e6b3ef6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257137/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257137/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257137/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..83047bf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257137/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257137/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257137/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257137/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257137/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257137/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257137/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257137/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257137/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257137/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257137/test.png b/data/CLs/finished/f1d1/bo5-+/2257137/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257137/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257138/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257138/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..989a715 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257138/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257138/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257138/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..251e38e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257138/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257138/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257138/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8b3d5d5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257138/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257138/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257138/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257138/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257138/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257138/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257138/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257138/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257138/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257138/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257138/test.png b/data/CLs/finished/f1d1/bo5-+/2257138/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257138/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257139/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257139/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..41673cd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257139/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257139/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257139/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d853411 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257139/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257139/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257139/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..946533a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257139/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257139/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257139/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257139/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257139/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257139/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257139/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257139/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257139/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257139/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257139/test.png b/data/CLs/finished/f1d1/bo5-+/2257139/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257139/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257140/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257140/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a9d65e5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257140/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257140/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257140/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c1c1beb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257140/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257140/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257140/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8a21a7d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257140/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257140/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257140/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257140/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257140/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257140/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257140/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257140/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257140/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257140/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257140/test.png b/data/CLs/finished/f1d1/bo5-+/2257140/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257140/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257141/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257141/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0db63ac --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257141/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257141/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257141/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0b62c3d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257141/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257141/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257141/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e993d14 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257141/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257141/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257141/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257141/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257141/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257141/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257141/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257141/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257141/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257141/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257141/test.png b/data/CLs/finished/f1d1/bo5-+/2257141/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257141/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257142/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257142/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0dd8e05 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257142/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257142/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257142/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a9ab736 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257142/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257142/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257142/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a225afa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257142/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257142/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257142/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257142/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257142/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257142/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257142/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257142/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257142/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257142/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257142/test.png b/data/CLs/finished/f1d1/bo5-+/2257142/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257142/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257143/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257143/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0e461d8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257143/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257143/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257143/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..819526d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257143/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257143/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257143/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3b4f02f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257143/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257143/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257143/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257143/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257143/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257143/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257143/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257143/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257143/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257143/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257143/test.png b/data/CLs/finished/f1d1/bo5-+/2257143/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257143/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257144/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257144/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..32ac403 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257144/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257144/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257144/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7f945c3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257144/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257144/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257144/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d551aad --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257144/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257144/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257144/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257144/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257144/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257144/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257144/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257144/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257144/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257144/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257144/test.png b/data/CLs/finished/f1d1/bo5-+/2257144/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257144/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257145/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257145/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cc0dfdb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257145/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257145/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257145/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..065d8dc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257145/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257145/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257145/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c9a4cb8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257145/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257145/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257145/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257145/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257145/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257145/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257145/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257145/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257145/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257145/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257145/test.png b/data/CLs/finished/f1d1/bo5-+/2257145/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257145/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257146/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257146/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..87d9f20 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257146/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257146/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257146/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ab800d8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257146/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257146/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257146/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5e89e3d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257146/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257146/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257146/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257146/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257146/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257146/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257146/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257146/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257146/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257146/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257146/test.png b/data/CLs/finished/f1d1/bo5-+/2257146/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257146/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257147/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257147/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cbd41f2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257147/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257147/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257147/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8327043 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257147/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257147/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257147/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a0b49a9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257147/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257147/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257147/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257147/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257147/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257147/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257147/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257147/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257147/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257147/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257147/test.png b/data/CLs/finished/f1d1/bo5-+/2257147/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257147/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257148/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257148/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9b1530e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257148/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257148/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257148/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8511b86 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257148/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257148/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257148/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..644bf75 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257148/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257148/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257148/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257148/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257148/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257148/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257148/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257148/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257148/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257148/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257148/test.png b/data/CLs/finished/f1d1/bo5-+/2257148/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257148/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257149/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257149/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a01ff04 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257149/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257149/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257149/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fdc0099 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257149/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257149/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257149/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f328ff8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257149/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257149/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257149/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257149/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257149/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257149/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257149/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257149/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257149/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257149/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257149/test.png b/data/CLs/finished/f1d1/bo5-+/2257149/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257149/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257150/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257150/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cb87e11 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257150/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257150/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257150/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..10b5127 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257150/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257150/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257150/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d8977d4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257150/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257150/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257150/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257150/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257150/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257150/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257150/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257150/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257150/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257150/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257150/test.png b/data/CLs/finished/f1d1/bo5-+/2257150/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257150/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257151/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257151/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4eb8bd1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257151/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257151/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257151/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..70474f8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257151/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257151/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257151/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b625c8b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257151/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257151/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257151/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257151/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257151/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257151/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257151/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257151/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257151/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257151/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257151/test.png b/data/CLs/finished/f1d1/bo5-+/2257151/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257151/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257152/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257152/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e11aec3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257152/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257152/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257152/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4566ccf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257152/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257152/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257152/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2fd5e7c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257152/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257152/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257152/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257152/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257152/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257152/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257152/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257152/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257152/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257152/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257152/test.png b/data/CLs/finished/f1d1/bo5-+/2257152/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257152/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257153/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257153/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e4d4e36 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257153/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257153/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257153/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..237bbd4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257153/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257153/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257153/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..26d7e60 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257153/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257153/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257153/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257153/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257153/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257153/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257153/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257153/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257153/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257153/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257153/test.png b/data/CLs/finished/f1d1/bo5-+/2257153/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257153/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257154/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257154/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..debbe38 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257154/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257154/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257154/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5ec8c22 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257154/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257154/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257154/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9c8050a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257154/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257154/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257154/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257154/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257154/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257154/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257154/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257154/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257154/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257154/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257154/test.png b/data/CLs/finished/f1d1/bo5-+/2257154/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257154/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257155/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257155/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..9ea1853 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257155/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257155/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257155/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..528dcae --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257155/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257155/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257155/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..92ccbba --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257155/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257155/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257155/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257155/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257155/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257155/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257155/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257155/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257155/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257155/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257155/test.png b/data/CLs/finished/f1d1/bo5-+/2257155/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257155/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257156/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257156/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7a28b72 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257156/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257156/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257156/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0e3a3b1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257156/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257156/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257156/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..da40c51 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257156/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257156/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257156/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257156/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257156/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257156/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257156/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257156/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257156/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257156/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257156/test.png b/data/CLs/finished/f1d1/bo5-+/2257156/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257156/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257157/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257157/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b8fa4c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257157/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257157/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257157/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a8ded65 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257157/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257157/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257157/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..86e9663 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257157/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257157/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257157/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257157/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257157/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257157/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257157/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257157/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257157/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257157/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257157/test.png b/data/CLs/finished/f1d1/bo5-+/2257157/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257157/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257158/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257158/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8ccbbb9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257158/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257158/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257158/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..17311a4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257158/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257158/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257158/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e266771 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257158/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257158/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257158/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257158/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257158/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257158/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257158/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257158/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257158/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257158/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257158/test.png b/data/CLs/finished/f1d1/bo5-+/2257158/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257158/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257159/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257159/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1e45f0a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257159/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257159/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257159/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..1768ee9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257159/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257159/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257159/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b7ba012 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257159/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257159/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257159/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257159/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257159/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257159/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257159/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257159/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257159/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257159/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257159/test.png b/data/CLs/finished/f1d1/bo5-+/2257159/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257159/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257160/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257160/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b9e0b56 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257160/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257160/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257160/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2cadda2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257160/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257160/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257160/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8c80f74 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257160/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257160/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257160/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257160/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257160/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257160/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257160/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257160/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257160/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257160/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257160/test.png b/data/CLs/finished/f1d1/bo5-+/2257160/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257160/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257161/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257161/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..31965ec --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257161/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257161/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257161/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ed139b5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257161/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257161/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257161/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..09d67bf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257161/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257161/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257161/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257161/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257161/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257161/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257161/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257161/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257161/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257161/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257161/test.png b/data/CLs/finished/f1d1/bo5-+/2257161/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257161/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257162/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257162/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..233508a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257162/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257162/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257162/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..19be7b5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257162/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257162/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257162/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..cd9f4e0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257162/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257162/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257162/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257162/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257162/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257162/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257162/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257162/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257162/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257162/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257162/test.png b/data/CLs/finished/f1d1/bo5-+/2257162/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257162/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257163/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257163/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..bad45d2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257163/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257163/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257163/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3248ebe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257163/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257163/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257163/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b99f248 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257163/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257163/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257163/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257163/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257163/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257163/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257163/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257163/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257163/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257163/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257163/test.png b/data/CLs/finished/f1d1/bo5-+/2257163/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257163/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257164/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257164/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..d721143 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257164/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257164/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257164/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b0d7055 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257164/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257164/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257164/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..1ca63b8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257164/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257164/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257164/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257164/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257164/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257164/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257164/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257164/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257164/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257164/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257164/test.png b/data/CLs/finished/f1d1/bo5-+/2257164/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257164/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257165/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257165/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7dac279 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257165/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257165/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257165/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5c97946 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257165/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257165/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257165/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..32122c2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257165/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257165/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257165/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257165/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257165/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257165/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257165/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257165/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257165/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257165/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257165/test.png b/data/CLs/finished/f1d1/bo5-+/2257165/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257165/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257166/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257166/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..eddad4c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257166/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257166/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257166/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..110acad --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257166/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257166/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257166/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8f1d7f5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257166/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257166/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257166/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257166/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257166/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257166/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257166/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257166/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257166/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257166/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257166/test.png b/data/CLs/finished/f1d1/bo5-+/2257166/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257166/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257167/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257167/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1559218 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257167/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257167/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257167/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4113d80 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257167/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257167/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257167/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2787796 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257167/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257167/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257167/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257167/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257167/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257167/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257167/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257167/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257167/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257167/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257167/test.png b/data/CLs/finished/f1d1/bo5-+/2257167/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257167/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257168/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257168/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..133c82e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257168/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257168/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257168/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..be2ee92 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257168/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257168/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257168/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..15dda94 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257168/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257168/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257168/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257168/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257168/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257168/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257168/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257168/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257168/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257168/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257168/test.png b/data/CLs/finished/f1d1/bo5-+/2257168/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257168/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257169/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257169/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6f1a98e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257169/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257169/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257169/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ffc8b16 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257169/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257169/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257169/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..041286e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257169/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257169/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257169/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257169/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257169/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257169/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257169/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257169/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257169/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257169/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257169/test.png b/data/CLs/finished/f1d1/bo5-+/2257169/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257169/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257170/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257170/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cedc2c7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257170/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257170/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257170/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ff8e818 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257170/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257170/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257170/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..5bcf065 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257170/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257170/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257170/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257170/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257170/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257170/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257170/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257170/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257170/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257170/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257170/test.png b/data/CLs/finished/f1d1/bo5-+/2257170/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257170/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257171/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257171/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6605ce0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257171/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257171/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257171/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..32bc49a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257171/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257171/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257171/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4d652e7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257171/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257171/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257171/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257171/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257171/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257171/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257171/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257171/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257171/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257171/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257171/test.png b/data/CLs/finished/f1d1/bo5-+/2257171/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257171/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257172/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257172/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..0b0d855 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257172/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257172/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257172/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5046269 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257172/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257172/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257172/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..870dd0c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257172/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257172/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257172/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257172/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257172/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257172/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257172/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257172/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257172/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257172/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257172/test.png b/data/CLs/finished/f1d1/bo5-+/2257172/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257172/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257173/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257173/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6202186 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257173/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257173/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257173/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3958f27 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257173/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257173/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257173/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3830d2f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257173/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257173/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257173/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257173/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257173/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257173/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257173/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257173/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257173/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257173/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257173/test.png b/data/CLs/finished/f1d1/bo5-+/2257173/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257173/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257174/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257174/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..012e615 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257174/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257174/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257174/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..6ae3dde --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257174/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257174/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257174/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..af680e3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257174/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257174/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257174/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257174/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257174/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257174/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257174/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257174/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257174/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257174/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257174/test.png b/data/CLs/finished/f1d1/bo5-+/2257174/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257174/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257175/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257175/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..999a3cf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257175/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257175/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257175/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5935a90 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257175/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257175/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257175/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..3d80c32 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257175/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257175/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257175/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257175/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257175/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257175/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257175/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257175/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257175/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257175/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257175/test.png b/data/CLs/finished/f1d1/bo5-+/2257175/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257175/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257176/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257176/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..24c10d5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257176/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257176/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257176/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f9f5118 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257176/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257176/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257176/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..946bb4e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257176/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257176/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257176/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257176/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257176/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257176/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257176/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257176/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257176/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257176/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257176/test.png b/data/CLs/finished/f1d1/bo5-+/2257176/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257176/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257177/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257177/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cdd355c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257177/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257177/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257177/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3dc1cd9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257177/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257177/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257177/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..05a0d40 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257177/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257177/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257177/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257177/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257177/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257177/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257177/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257177/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257177/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257177/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257177/test.png b/data/CLs/finished/f1d1/bo5-+/2257177/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257177/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257178/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257178/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7842fc4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257178/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257178/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257178/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7baeadf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257178/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257178/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257178/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f1513bd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257178/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257178/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257178/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257178/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257178/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257178/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257178/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257178/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257178/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257178/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257178/test.png b/data/CLs/finished/f1d1/bo5-+/2257178/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257178/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257179/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257179/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6f1a67b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257179/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257179/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257179/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..da4a904 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257179/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257179/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257179/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ebc6f45 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257179/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257179/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257179/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257179/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257179/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257179/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257179/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257179/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257179/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257179/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257179/test.png b/data/CLs/finished/f1d1/bo5-+/2257179/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257179/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257180/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257180/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ee6190c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257180/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257180/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257180/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ac9ced2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257180/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257180/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257180/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0b7cc61 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257180/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257180/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257180/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257180/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257180/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257180/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257180/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257180/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257180/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257180/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257180/test.png b/data/CLs/finished/f1d1/bo5-+/2257180/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257180/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257181/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257181/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..28b2202 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257181/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257181/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257181/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3416407 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257181/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257181/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257181/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0520e5b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257181/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257181/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257181/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257181/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257181/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257181/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257181/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257181/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257181/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257181/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257181/test.png b/data/CLs/finished/f1d1/bo5-+/2257181/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257181/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257182/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257182/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2f25b0e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257182/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257182/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257182/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8d31385 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257182/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257182/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257182/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9b2c6ee --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257182/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257182/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257182/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257182/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257182/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257182/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257182/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257182/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257182/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257182/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257182/test.png b/data/CLs/finished/f1d1/bo5-+/2257182/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257182/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257183/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257183/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..ae7b3f3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257183/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257183/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257183/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..5a23c2b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257183/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257183/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257183/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..b5fb0c4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257183/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257183/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257183/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257183/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257183/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257183/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257183/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257183/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257183/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257183/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257183/test.png b/data/CLs/finished/f1d1/bo5-+/2257183/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257183/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257184/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257184/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..133991d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257184/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257184/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257184/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..49a01f0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257184/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257184/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257184/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..51365a3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257184/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257184/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257184/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257184/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257184/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257184/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257184/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257184/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257184/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257184/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257184/test.png b/data/CLs/finished/f1d1/bo5-+/2257184/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257184/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257185/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257185/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6f48e91 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257185/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257185/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257185/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..f7e5091 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257185/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257185/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257185/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..69dc3c2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257185/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257185/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257185/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257185/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257185/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257185/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257185/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257185/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257185/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257185/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257185/test.png b/data/CLs/finished/f1d1/bo5-+/2257185/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257185/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257186/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257186/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e9fabee --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257186/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257186/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257186/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b9514fa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257186/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257186/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257186/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..bccef2e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257186/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257186/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257186/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257186/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257186/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257186/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257186/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257186/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257186/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257186/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257186/test.png b/data/CLs/finished/f1d1/bo5-+/2257186/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257186/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257187/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257187/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..64221ab --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257187/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257187/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257187/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..59ab905 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257187/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257187/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257187/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ff4d726 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257187/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257187/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257187/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257187/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257187/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257187/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257187/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257187/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257187/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257187/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257187/test.png b/data/CLs/finished/f1d1/bo5-+/2257187/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257187/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257188/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257188/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2795732 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257188/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257188/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257188/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..023c789 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257188/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257188/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257188/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..ce7b081 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257188/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257188/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257188/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257188/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257188/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257188/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257188/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257188/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257188/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257188/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257188/test.png b/data/CLs/finished/f1d1/bo5-+/2257188/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257188/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257189/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257189/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..28cf8d7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257189/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257189/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257189/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9c4003e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257189/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257189/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257189/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c46b8ec --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257189/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257189/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257189/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257189/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257189/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257189/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257189/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257189/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257189/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257189/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257189/test.png b/data/CLs/finished/f1d1/bo5-+/2257189/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257189/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257190/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257190/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..492ba30 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257190/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257190/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257190/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..6d5c971 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257190/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257190/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257190/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9f2246c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257190/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257190/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257190/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257190/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257190/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257190/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257190/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257190/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257190/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257190/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257190/test.png b/data/CLs/finished/f1d1/bo5-+/2257190/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257190/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257191/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257191/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b959be3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257191/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257191/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257191/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..62eed8b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257191/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257191/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257191/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0fc7d25 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257191/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257191/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257191/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257191/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257191/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257191/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257191/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257191/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257191/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257191/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257191/test.png b/data/CLs/finished/f1d1/bo5-+/2257191/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257191/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257192/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257192/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6ee8040 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257192/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257192/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257192/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a52ff0b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257192/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257192/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257192/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..a73d2d4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257192/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257192/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257192/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257192/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257192/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257192/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257192/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257192/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257192/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257192/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257192/test.png b/data/CLs/finished/f1d1/bo5-+/2257192/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257192/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257193/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257193/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c1a2bbe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257193/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257193/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257193/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a86fb2b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257193/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257193/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257193/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e1fb7c7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257193/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257193/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257193/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257193/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257193/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257193/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257193/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257193/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257193/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257193/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257193/test.png b/data/CLs/finished/f1d1/bo5-+/2257193/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257193/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257194/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257194/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..4ef7a7d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257194/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257194/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257194/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..66af900 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257194/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257194/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257194/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..75e4b75 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257194/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257194/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257194/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257194/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257194/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257194/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257194/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257194/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257194/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257194/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257194/test.png b/data/CLs/finished/f1d1/bo5-+/2257194/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257194/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257195/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257195/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..27d279b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257195/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257195/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257195/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4f43d6c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257195/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257195/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257195/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..31ed93a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257195/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257195/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257195/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257195/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257195/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257195/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257195/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257195/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257195/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257195/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257195/test.png b/data/CLs/finished/f1d1/bo5-+/2257195/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257195/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257196/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257196/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a867488 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257196/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257196/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257196/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8149479 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257196/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257196/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257196/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..33ec3e2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257196/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257196/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257196/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257196/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257196/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257196/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257196/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257196/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257196/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257196/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257196/test.png b/data/CLs/finished/f1d1/bo5-+/2257196/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257196/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257197/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257197/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6c4d3f4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257197/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257197/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257197/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..126e624 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257197/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257197/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257197/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..221ff0d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257197/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257197/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257197/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257197/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257197/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257197/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257197/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257197/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257197/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257197/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257197/test.png b/data/CLs/finished/f1d1/bo5-+/2257197/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257197/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257198/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257198/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..83f2bc9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257198/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257198/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257198/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..3713510 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257198/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257198/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257198/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d437491 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257198/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257198/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257198/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257198/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257198/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257198/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257198/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257198/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257198/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257198/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257198/test.png b/data/CLs/finished/f1d1/bo5-+/2257198/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257198/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257199/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257199/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7e5eb32 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257199/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257199/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257199/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ab7331d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257199/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257199/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257199/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..118f1ff --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257199/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257199/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257199/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257199/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257199/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257199/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257199/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257199/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257199/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257199/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257199/test.png b/data/CLs/finished/f1d1/bo5-+/2257199/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257199/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257200/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257200/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..20dc025 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257200/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257200/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257200/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..feda448 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257200/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257200/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257200/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..25d06eb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257200/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257200/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257200/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257200/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257200/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257200/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257200/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257200/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257200/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257200/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257200/test.png b/data/CLs/finished/f1d1/bo5-+/2257200/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257200/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257201/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257201/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..15a2825 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257201/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257201/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257201/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..668ab53 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257201/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257201/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257201/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..639e8cf --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257201/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257201/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257201/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257201/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257201/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257201/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257201/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257201/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257201/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257201/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257201/test.png b/data/CLs/finished/f1d1/bo5-+/2257201/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257201/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257202/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257202/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6bd60af --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257202/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257202/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257202/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..46d9319 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257202/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257202/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257202/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0096429 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257202/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257202/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257202/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257202/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257202/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257202/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257202/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257202/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257202/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257202/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257202/test.png b/data/CLs/finished/f1d1/bo5-+/2257202/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257202/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257203/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257203/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..282ccd6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257203/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257203/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257203/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..c7c639a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257203/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257203/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257203/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f854a35 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257203/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257203/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257203/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257203/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257203/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257203/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257203/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257203/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257203/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257203/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257203/test.png b/data/CLs/finished/f1d1/bo5-+/2257203/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257203/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257204/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257204/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..b23700d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257204/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257204/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257204/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cb8cf7a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257204/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257204/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257204/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f1cf4b5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257204/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257204/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257204/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257204/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257204/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257204/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257204/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257204/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257204/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257204/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257204/test.png b/data/CLs/finished/f1d1/bo5-+/2257204/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257204/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257205/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257205/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..86c8af9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257205/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257205/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257205/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ef3952d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257205/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257205/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257205/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2f3c404 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257205/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257205/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257205/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257205/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257205/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257205/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257205/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257205/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257205/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257205/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257205/test.png b/data/CLs/finished/f1d1/bo5-+/2257205/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257205/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257206/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257206/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2ddf7d7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257206/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257206/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257206/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7407a8c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257206/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257206/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257206/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..12d61eb --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257206/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257206/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257206/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257206/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257206/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257206/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257206/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257206/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257206/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257206/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257206/test.png b/data/CLs/finished/f1d1/bo5-+/2257206/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257206/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257207/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257207/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..eefb41d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257207/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257207/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257207/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a58eda4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257207/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257207/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257207/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2ebbad7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257207/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257207/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257207/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257207/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257207/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257207/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257207/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257207/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257207/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257207/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257207/test.png b/data/CLs/finished/f1d1/bo5-+/2257207/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257207/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257208/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257208/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c2f033c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257208/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257208/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257208/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..90ccca5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257208/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257208/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257208/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..da23783 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257208/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257208/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257208/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257208/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257208/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257208/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257208/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257208/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257208/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257208/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257208/test.png b/data/CLs/finished/f1d1/bo5-+/2257208/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257208/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257209/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257209/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..55e9c1b --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257209/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257209/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257209/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..319d07d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257209/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257209/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257209/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..9cacd18 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257209/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257209/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257209/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257209/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257209/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257209/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257209/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257209/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257209/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257209/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257209/test.png b/data/CLs/finished/f1d1/bo5-+/2257209/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257209/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257210/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257210/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..97ad2aa --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257210/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257210/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257210/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7035792 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257210/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257210/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257210/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..f45ec7f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257210/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257210/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257210/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257210/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257210/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257210/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257210/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257210/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257210/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257210/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257210/test.png b/data/CLs/finished/f1d1/bo5-+/2257210/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257210/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257211/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257211/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2aaf145 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257211/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257211/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257211/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..93fdced --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257211/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257211/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257211/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..c5aaf78 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257211/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257211/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257211/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257211/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257211/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257211/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257211/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257211/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257211/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257211/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257211/test.png b/data/CLs/finished/f1d1/bo5-+/2257211/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257211/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257212/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257212/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..6ae5683 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257212/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257212/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257212/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b09bdd8 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257212/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257212/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257212/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..2a5b8a2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257212/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257212/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257212/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257212/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257212/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257212/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257212/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257212/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257212/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257212/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257212/test.png b/data/CLs/finished/f1d1/bo5-+/2257212/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257212/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257213/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257213/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..19f4e1f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257213/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257213/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257213/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..a1256a7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257213/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257213/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257213/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..89bcbc0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257213/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257213/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257213/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257213/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257213/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257213/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257213/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257213/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257213/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257213/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257213/test.png b/data/CLs/finished/f1d1/bo5-+/2257213/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257213/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257214/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257214/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dd550a5 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257214/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257214/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257214/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0869a39 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257214/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257214/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257214/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..e47e743 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257214/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257214/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257214/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257214/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257214/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257214/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257214/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257214/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257214/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257214/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257214/test.png b/data/CLs/finished/f1d1/bo5-+/2257214/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257214/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257215/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257215/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c5e517d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257215/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257215/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257215/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cbd2a1c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257215/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257215/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257215/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..47d69d6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257215/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257215/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257215/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257215/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257215/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257215/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257215/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257215/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257215/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257215/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257215/test.png b/data/CLs/finished/f1d1/bo5-+/2257215/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257215/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257216/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257216/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..839b881 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257216/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257216/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257216/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..7a642de --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257216/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257216/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257216/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..4747fe2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257216/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257216/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257216/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257216/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257216/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257216/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257216/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257216/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257216/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257216/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257216/test.png b/data/CLs/finished/f1d1/bo5-+/2257216/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257216/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257217/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257217/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..a75eaa4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257217/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257217/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257217/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..b0e5dec --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257217/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257217/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257217/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..cff26d3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257217/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257217/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257217/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257217/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257217/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257217/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257217/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257217/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257217/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257217/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257217/test.png b/data/CLs/finished/f1d1/bo5-+/2257217/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257217/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257218/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257218/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..185d380 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257218/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257218/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257218/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..535b671 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257218/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257218/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257218/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..70fea6c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257218/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257218/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257218/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257218/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257218/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257218/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257218/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257218/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257218/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257218/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257218/test.png b/data/CLs/finished/f1d1/bo5-+/2257218/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257218/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257219/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257219/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..dff2138 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257219/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257219/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257219/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..00a1cb3 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257219/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257219/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257219/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..43b82be --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257219/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257219/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257219/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257219/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257219/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257219/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257219/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257219/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257219/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257219/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257219/test.png b/data/CLs/finished/f1d1/bo5-+/2257219/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257219/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257220/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257220/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7a1d352 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257220/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257220/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257220/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..8e3354c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257220/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257220/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257220/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..da42544 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257220/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257220/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257220/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257220/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257220/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257220/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257220/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257220/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257220/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257220/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257220/test.png b/data/CLs/finished/f1d1/bo5-+/2257220/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257220/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257221/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257221/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1360ca9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257221/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257221/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257221/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ca2cf78 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257221/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257221/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257221/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..84a51d1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257221/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257221/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257221/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257221/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257221/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257221/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257221/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257221/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257221/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257221/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257221/test.png b/data/CLs/finished/f1d1/bo5-+/2257221/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257221/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257222/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257222/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..cbe0f44 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257222/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257222/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257222/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..9f68ada --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257222/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257222/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257222/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..fde92d2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257222/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257222/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257222/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257222/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257222/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257222/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257222/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257222/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257222/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257222/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257222/test.png b/data/CLs/finished/f1d1/bo5-+/2257222/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257222/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257223/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257223/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2dd70e7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257223/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257223/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257223/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..68cb710 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257223/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257223/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257223/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..33392b4 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257223/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257223/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257223/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257223/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257223/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257223/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257223/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257223/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257223/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257223/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257223/test.png b/data/CLs/finished/f1d1/bo5-+/2257223/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257223/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257224/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257224/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..04be516 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257224/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257224/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257224/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..ae33bd6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257224/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257224/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257224/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..aad70f0 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257224/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257224/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257224/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257224/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257224/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257224/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257224/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257224/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257224/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257224/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257224/test.png b/data/CLs/finished/f1d1/bo5-+/2257224/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257224/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257225/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257225/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..2c8b837 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257225/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257225/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257225/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4bd83fe --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257225/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257225/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257225/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..d2b01f9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257225/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257225/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257225/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257225/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257225/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257225/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257225/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257225/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257225/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257225/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257225/test.png b/data/CLs/finished/f1d1/bo5-+/2257225/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257225/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257226/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257226/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..3c4963f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257226/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257226/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257226/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4a4f81e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257226/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257226/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257226/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..707f91d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257226/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257226/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257226/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257226/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257226/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257226/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257226/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257226/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257226/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257226/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257226/test.png b/data/CLs/finished/f1d1/bo5-+/2257226/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257226/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257227/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257227/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..304ea6c --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257227/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257227/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257227/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..14f5284 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257227/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257227/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257227/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0c81a57 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257227/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257227/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257227/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257227/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257227/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257227/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257227/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257227/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257227/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257227/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257227/test.png b/data/CLs/finished/f1d1/bo5-+/2257227/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257227/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257228/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257228/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..5c4647a --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257228/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257228/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257228/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..d189293 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257228/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257228/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257228/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..82d2ea7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257228/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257228/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257228/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257228/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257228/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257228/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257228/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257228/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257228/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257228/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257228/test.png b/data/CLs/finished/f1d1/bo5-+/2257228/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257228/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257229/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257229/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7816478 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257229/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257229/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257229/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..027959d --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257229/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257229/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257229/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..8c19efc --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257229/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257229/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257229/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257229/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257229/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257229/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257229/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257229/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257229/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257229/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257229/test.png b/data/CLs/finished/f1d1/bo5-+/2257229/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257229/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257230/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257230/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..8759db1 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257230/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257230/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257230/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..4dc0fa2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257230/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257230/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257230/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..7b9aea9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257230/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257230/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257230/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257230/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257230/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257230/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257230/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257230/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257230/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257230/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257230/test.png b/data/CLs/finished/f1d1/bo5-+/2257230/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257230/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257231/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257231/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..40007ef --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257231/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257231/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257231/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..0856704 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257231/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257231/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257231/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..0386173 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257231/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257231/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257231/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257231/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257231/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257231/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257231/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257231/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257231/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257231/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257231/test.png b/data/CLs/finished/f1d1/bo5-+/2257231/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257231/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257232/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257232/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..7b6bed9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257232/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257232/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257232/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..fcece0f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257232/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257232/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257232/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..67a2c2f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257232/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257232/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257232/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257232/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257232/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257232/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257232/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257232/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257232/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257232/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257232/test.png b/data/CLs/finished/f1d1/bo5-+/2257232/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257232/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257233/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257233/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..1d56657 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257233/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257233/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257233/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cb93273 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257233/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257233/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257233/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..eae0ce2 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257233/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257233/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257233/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257233/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257233/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257233/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257233/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257233/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257233/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257233/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257233/test.png b/data/CLs/finished/f1d1/bo5-+/2257233/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257233/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257234/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257234/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..c88e012 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257234/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257234/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257234/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..2154ff6 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257234/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257234/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257234/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..00d40dd --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257234/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257234/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257234/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257234/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257234/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257234/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257234/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257234/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257234/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257234/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257234/test.png b/data/CLs/finished/f1d1/bo5-+/2257234/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257234/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257235/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257235/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..e552156 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257235/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257235/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257235/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..e10b258 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257235/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257235/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257235/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..353e7f9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257235/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257235/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257235/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257235/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257235/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257235/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257235/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257235/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257235/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257235/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257235/test.png b/data/CLs/finished/f1d1/bo5-+/2257235/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257235/test.png Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257236/__pycache__/helperfunctions.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257236/__pycache__/helperfunctions.cpython-37.pyc new file mode 100644 index 0000000..27cd2c9 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257236/__pycache__/helperfunctions.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257236/__pycache__/pdg_const.cpython-37.pyc b/data/CLs/finished/f1d1/bo5-+/2257236/__pycache__/pdg_const.cpython-37.pyc new file mode 100644 index 0000000..cd56223 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257236/__pycache__/pdg_const.cpython-37.pyc Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257236/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl b/data/CLs/finished/f1d1/bo5-+/2257236/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl new file mode 100644 index 0000000..af15044 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257236/data/CLs/0.0-0.001_11s--CLs_Nll_list.pkl Binary files differ diff --git a/data/CLs/finished/f1d1/bo5-+/2257236/helperfunctions.py b/data/CLs/finished/f1d1/bo5-+/2257236/helperfunctions.py new file mode 100644 index 0000000..88e120f --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257236/helperfunctions.py @@ -0,0 +1,33 @@ +# some helperfunctions + +import matplotlib +matplotlib.use("agg") +import matplotlib.pyplot as plt + +#Dislpay time (e.g. while generating points) + +display_intervals = ( + ('w', 604800), # 60 * 60 * 24 * 7 + ('d', 86400), # 60 * 60 * 24 + ('h', 3600), # 60 * 60 + ('min', 60), + ('s', 1), + ) + +def display_time(seconds, granularity=2): + result = [] + + for name, count in display_intervals: + value = seconds // count + if value: + seconds -= value * count + if value == 1: + name = name.rstrip('s') + result.append("{} {}".format(value, name)) + return ', '.join(result[:granularity]) + +def prepare_plot(title): + plt.title(title) + plt.grid() + plt.legend(loc = 'best') + plt.xlabel("q") diff --git a/data/CLs/finished/f1d1/bo5-+/2257236/pdg_const.py b/data/CLs/finished/f1d1/bo5-+/2257236/pdg_const.py new file mode 100644 index 0000000..6645dd7 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257236/pdg_const.py @@ -0,0 +1,226 @@ +pdg = { + + + ###Particle masses### + + "mbstar" : 5415.4, + "mbstar0" : 5711.0, + "B0_M" : 5279.5, + "Bs_M" : 5366.7, + "Bplus_M" : 5279.3, + "Lb_M" : 5619.4, + "D0_M" : 1864.8, + "Dst_M" : 2010, + "pi_M" : 139.6, + "Jpsi_M" : 3096.9, + "Psi2s_M" : 3685.6, + "kaon_M" : 493.7, + "Ks_M" : 497.6, + "phi_M" : 1019.5, + "rho_M" : 775.26, + "rho_width" : 149.1, + "omega_M" : 782.65, + "omega_width" : 8.49, + + "muon_M" : 105.7, + "tau_M": 1776.86, + + "squark_M" : 95.0, + "bquark_M" : 4180.0, + "cquark_M" : 1275.0, + + "Bplus_tau" : 1.638e-12, + + ###Wilson coefficients### + + "C1" : -0.257, + "C2" : 1.009, + "C3" : -0.005, + "C4" : -0.078, + + "C7eff" : -0.306, + "C9eff" : 4.211, + "C10eff" : -4.103, + +# "C7eff": 0.0, +# "C9eff": 0.0, +# "C10eff": 0.0, + + ###Other constants + + "GF" : 1.1663787e-5, + "alpha_ew" : 1.0/137.0, + "Vts" : 0.0394, + "Vtb" : 1.019, + "number_of_decays": 5404696, + + #Formfactor z coefficients + + #"b0" : [0.285, 0.19, -0.17], + #"bplus" : [0.437, -1.41, -2.5], + #"bT" : [0.440, -1.47, -2.7] + + "b0" : [0.292, 0.281, 0.150], + "bplus" : [0.466, -0.885, -0.213], + "bT" : [0.460, -1.089, -1.114], + + "NR_BR": 4.37e-7, + "NR_auc": 0.00133, + + #Resonances format(mass, width, phase, scale) + + # pre scaling + +# "rho": (775.26, 149.0, -0.35, 1.0), + +# "omega": (782.7, 8.5, 0.26, 1.0), + +# "phi": (1019.46, 4.25, 0.5, 1.0), + +# "jpsi": (3096.0, 0.09, -1.5, 2e-2), +# "jpsi_auc": 0.2126825758464027, + +# "psi2s": (3686.0, 0.3, -1.5, 3.14e-3), +# "psi2s_auc": 2.802257483178487e-10, + +# "p3770": (3773.0, 27.2, -2.13, 1.0e-3), + +# "p4040": (4039.0, 80.0, -2.52, 2.0), + +# "p4160": (4191.0, 70.0, -1.9, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.0), + + + # after scaling (Phase combination --) + + +# "rho": (743.2, 149.0, -0.22, 1.05), + +# "omega": (782.7, 8.5, 0.38, 6.8), + +# "phi": (1013.5, 4.25, 0.62, 19.2), + +# "jpsi": (3096.1, 0.09, 1.63, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, 1.8, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.95, 2.5), + +# "p4040": (4039.0, 80.0, -2.75, 1.01), + +# "p4160": (4191.0, 70.0, -2.28, 2.2), + +# "p4415": (4421.0, 62.0, -2.31, 1.24), + + # Phase combination of paper ++ + +# "rho": (743.2, 149.0, -0.35, 1.05), + +# "omega": (782.7, 8.5, 0.26, 6.8), + +# "phi": (1013.5, 4.25, 0.47, 19.2), + +# "jpsi": (3096.1, 0.09, -1.66, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -1.93, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.13, 2.5), + +# "p4040": (4039.0, 80.0, -2.52, 1.01), + +# "p4160": (4191.0, 70.0, -1.90, 2.2), + +# "p4415": (4421.0, 62.0, -2.52, 1.24), + + # Phase combination of paper +- + + # "rho": (743.2, 149.0, -0.26, 1.05), + # + # "omega": (782.7, 8.5, 0.35, 6.8), + # + # "phi": (1013.5, 4.25, 0.58, 19.2), + # + # "jpsi": (3096.1, 0.09, 1.47, 9897.0), + # "jpsi_auc": 0.2126825758464027, + # "jpsi_phase_unc": 0.05, + # + # "psi2s": (3686.0, 0.3, -2.21, 1396.0), + # "psi2s_auc": 0.0151332263, + # "psi2s_phase_unc": 0.1, + # + # "p3770": (3773.0, 27.2, -2.140, 2.5), + # + # "p4040": (4039.0, 80.0, -2.64, 1.01), + # + # "p4160": (4191.0, 70.0, -2.11, 2.2), + # + # "p4415": (4421.0, 62.0, -2.42, 1.24), + + # Phase combination of paper -+ + + "rho": (743.2, 149.0, -0.30, 1.05), + + "omega": (782.7, 8.5, 0.30, 6.8), + + "phi": (1013.5, 4.25, 0.51, 19.2), + + "jpsi": (3096.1, 0.09, -1.5, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, + + "psi2s": (3686.0, 0.3, 2.08, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, + + "p3770": (3773.0, 27.2, -2.89, 2.5), + + "p4040": (4039.0, 80.0, -2.69, 1.01), + + "p4160": (4191.0, 70.0, -2.13, 2.2), + + "p4415": (4421.0, 62.0, -2.43, 1.24), + + + # zeroing resonances + +# "rho": (775.26, 149.0, -0.35, 0.0), +# "omega": (782.7, 8.5, 0.26, 0.0), +# "phi": (1019.46, 4.25, 0.5, 0.0), +# "jpsi": (3096.0, 0.09, -1.5, 0.0), +# "psi2s": (3686.0, 0.3, -1.5, 0.0), +# "p3770": (3773.0, 27.2, -2.13, 0.0), +# "p4040": (4039.0, 80.0, -2.52, 0.0), +# "p4160": (4147.0, 22.0, -1.9, 0.0), +# "p4415": (4421.0, 62.0, -2.52, 0.0), + + # 2P contributions format(mass, amp, phase) + +# "D_bar": ( + + #general + + "rho_BR": 1.7e-10, + "omega_BR": 4.9e-10, + "phi_BR": 2.5e-9, + "jpsi_BR": 6.02e-5, + "psi2s_BR": 4.97e-6, + "p3770_BR": 1.38e-9, + "p4040_BR": 4.2e-10, + "p4160_BR": 2.6e-9, + "p4415_BR": 6.1e-10, + +# Estimates + "Dbar_scale": 1.46, #with phase = pi + + "DDstar_scale": 2.41, #with phase = pi + + } diff --git a/data/CLs/finished/f1d1/bo5-+/2257236/raremodel-nb.py b/data/CLs/finished/f1d1/bo5-+/2257236/raremodel-nb.py new file mode 100644 index 0000000..c93081e --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257236/raremodel-nb.py @@ -0,0 +1,1944 @@ +#!/usr/bin/env python +# coding: utf-8 + +# # Import + +# In[1]: + + +import os + +# os.environ["CUDA_VISIBLE_DEVICES"] = "-1" + +import numpy as np +from pdg_const import pdg +import matplotlib +import matplotlib.pyplot as plt +import pickle as pkl +import sys +import time +from helperfunctions import display_time, prepare_plot +import cmath as c +import scipy.integrate as integrate +from scipy.optimize import fminbound +from array import array as arr +import collections +from itertools import compress +import tensorflow as tf +import zfit +from zfit import ztf +# from IPython.display import clear_output +import os +import tensorflow_probability as tfp +tfd = tfp.distributions + + +# In[2]: + + +# chunksize = 10000 +# zfit.run.chunking.active = True +# zfit.run.chunking.max_n_points = chunksize + + +# # Build model and graphs +# ## Create graphs + +# In[ ]: + + + + + +# In[3]: + + +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 + #check if subscript is viable + + if subscript != "0" and subscript != "+" and subscript != "T": + raise ValueError('Wrong subscript entered, choose either 0, + or T') + + #get constants + + mK = ztf.constant(pdg['Ks_M']) + mbstar0 = ztf.constant(pdg["mbstar0"]) + mbstar = ztf.constant(pdg["mbstar"]) + + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #N comes from derivation in paper + + N = 3 + + #some helperfunctions + + tpos = (mB - mK)**2 + tzero = (mB + mK)*(ztf.sqrt(mB)-ztf.sqrt(mK))**2 + + z_oben = ztf.sqrt(tpos - q2) - ztf.sqrt(tpos - tzero) + z_unten = ztf.sqrt(tpos - q2) + ztf.sqrt(tpos - tzero) + z = tf.divide(z_oben, z_unten) + + #calculate f0 + + if subscript == "0": + prefactor = 1/(1 - q2/(mbstar0**2)) + _sum = 0 + b0 = [b0_0, b0_1, b0_2] + + for i in range(N): + _sum += b0[i]*(tf.pow(z,i)) + + return ztf.to_complex(prefactor * _sum) + + #calculate f+ or fT + + else: + prefactor = 1/(1 - q2/(mbstar**2)) + _sum = 0 + + if subscript == "T": + bT = [bT_0, bT_1, bT_2] + for i in range(N): + _sum += bT[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + else: + bplus = [bplus_0, bplus_1, bplus_2] + for i in range(N): + _sum += bplus[i] * (tf.pow(z, i) - ((-1)**(i-N)) * (i/N) * tf.pow(z, N)) + + return ztf.to_complex(prefactor * _sum) + +def resonance(q, _mass, width, phase, scale): + + q2 = tf.pow(q, 2) + + mmu = ztf.constant(pdg['muon_M']) + + p = 0.5 * ztf.sqrt(q2 - 4*(mmu**2)) + + p0 = 0.5 * ztf.sqrt(_mass**2 - 4*mmu**2) + + gamma_j = tf.divide(p, q) * _mass * width / p0 + + #Calculate the resonance + + _top = tf.complex(_mass * width, ztf.constant(0.0)) + + _bottom = tf.complex(_mass**2 - q2, -_mass*gamma_j) + + com = _top/_bottom + + #Rotate by the phase + + r = ztf.to_complex(scale*tf.abs(com)) + + _phase = tf.angle(com) + + _phase += phase + + com = r * tf.exp(tf.complex(ztf.constant(0.0), _phase)) + + return com + + +def axiv_nonres(q, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C10eff = ztf.constant(pdg['C10eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + q2 = tf.pow(q, 2) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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.) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2. * kabs * beta / (128. * np.pi**5.) + + #left term in bracket + + 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) + + #middle term in bracket + + _top = 4. * mmu**2. * (mB**2. - mK**2.) * (mB**2. - mK**2.) + + _under = q2 * mB**2. + + 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) + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * (bracket_left + bracket_middle) * 2 * q + +def vec(q, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2): + + q2 = tf.pow(q, 2) + + GF = ztf.constant(pdg['GF']) + alpha_ew = ztf.constant(pdg['alpha_ew']) + Vtb = ztf.constant(pdg['Vtb']) + Vts = ztf.constant(pdg['Vts']) + C7eff = ztf.constant(pdg['C7eff']) + + mmu = ztf.constant(pdg['muon_M']) + mb = ztf.constant(pdg['bquark_M']) + ms = ztf.constant(pdg['squark_M']) + mK = ztf.constant(pdg['Ks_M']) + mB = ztf.constant(pdg['Bplus_M']) + + #Some helperfunctions + + beta = 1. - 4. * mmu**2. / q2 + + 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) + + #prefactor in front of whole bracket + + prefactor1 = GF**2. *alpha_ew**2. * (tf.abs(Vtb*Vts))**2 * kabs * beta / (128. * np.pi**5.) + + #right term in bracket + + prefactor2 = tf.pow(kabs,2) * (1. - 1./3. * beta) + + 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) + + bracket_right = prefactor2 * abs_bracket + + #Note sqrt(q2) comes from derivation as we use q2 and plot q + + return prefactor1 * bracket_right * 2 * q + +def c9eff(q, funcs): + + C9eff_nr = ztf.to_complex(ztf.constant(pdg['C9eff'])) + + c9 = C9eff_nr + funcs + + return c9 + + +# In[4]: + + +def G(y): + + def inner_rect_bracket(q): + return tf.log(ztf.to_complex((1+tf.sqrt(q))/(1-tf.sqrt(q)))-tf.complex(ztf.constant(0), -1*ztf.constant(np.pi))) + + def inner_right(q): + return ztf.to_complex(2 * tf.atan(1/tf.sqrt(tf.math.real(-q)))) + + big_bracket = tf.where(tf.math.real(y) > ztf.constant(0.0), inner_rect_bracket(y), inner_right(y)) + + return ztf.to_complex(tf.sqrt(tf.abs(y))) * big_bracket + +def h_S(m, q): + + 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))) + +def h_P(m, q): + + 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) + +def two_p_ccbar(mD, m_D_bar, m_D_star, q): + + + #Load constants + nu_D_bar = ztf.to_complex(pdg["nu_D_bar"]) + nu_D = ztf.to_complex(pdg["nu_D"]) + nu_D_star = ztf.to_complex(pdg["nu_D_star"]) + + phase_D_bar = ztf.to_complex(pdg["phase_D_bar"]) + phase_D = ztf.to_complex(pdg["phase_D"]) + phase_D_star = ztf.to_complex(pdg["phase_D_star"]) + + #Calculation + left_part = nu_D_bar * tf.exp(tf.complex(ztf.constant(0.0), phase_D_bar)) * h_S(m_D_bar, q) + + right_part_D = nu_D * tf.exp(tf.complex(ztf.constant(0.0), phase_D)) * h_P(m_D, q) + + right_part_D_star = nu_D_star * tf.exp(tf.complex(ztf.constant(0.0), phase_D_star)) * h_P(m_D_star, q) + + return left_part + right_part_D + right_part_D_star + + +# ## Build pdf + +# In[5]: + + +class total_pdf_cut(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + + tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + + tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + +class total_pdf_full(zfit.pdf.ZPDF): + _N_OBS = 1 # dimension, can be omitted + _PARAMS = ['b0_0', 'b0_1', 'b0_2', + 'bplus_0', 'bplus_1', 'bplus_2', + 'bT_0', 'bT_1', 'bT_2', + 'rho_mass', 'rho_scale', 'rho_phase', 'rho_width', + 'jpsi_mass', 'jpsi_scale', 'jpsi_phase', 'jpsi_width', + 'psi2s_mass', 'psi2s_scale', 'psi2s_phase', 'psi2s_width', + 'p3770_mass', 'p3770_scale', 'p3770_phase', 'p3770_width', + 'p4040_mass', 'p4040_scale', 'p4040_phase', 'p4040_width', + 'p4160_mass', 'p4160_scale', 'p4160_phase', 'p4160_width', + 'p4415_mass', 'p4415_scale', 'p4415_phase', 'p4415_width', + 'omega_mass', 'omega_scale', 'omega_phase', 'omega_width', + 'phi_mass', 'phi_scale', 'phi_phase', 'phi_width', + 'Dbar_mass', 'Dbar_scale', 'Dbar_phase', + 'Dstar_mass', 'DDstar_scale', 'DDstar_phase', 'D_mass', + 'tau_mass', 'C_tt'] +# the name of the parameters + + def _unnormalized_pdf(self, x): + + x = x.unstack_x() + + b0 = [self.params['b0_0'], self.params['b0_1'], self.params['b0_2']] + bplus = [self.params['bplus_0'], self.params['bplus_1'], self.params['bplus_2']] + bT = [self.params['bT_0'], self.params['bT_1'], self.params['bT_2']] + + def rho_res(q): + return resonance(q, _mass = self.params['rho_mass'], scale = self.params['rho_scale'], + phase = self.params['rho_phase'], width = self.params['rho_width']) + + def omega_res(q): + return resonance(q, _mass = self.params['omega_mass'], scale = self.params['omega_scale'], + phase = self.params['omega_phase'], width = self.params['omega_width']) + + def phi_res(q): + return resonance(q, _mass = self.params['phi_mass'], scale = self.params['phi_scale'], + phase = self.params['phi_phase'], width = self.params['phi_width']) + + def jpsi_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['jpsi_mass'], 2)) * resonance(q, _mass = self.params['jpsi_mass'], + scale = self.params['jpsi_scale'], + phase = self.params['jpsi_phase'], + width = self.params['jpsi_width']) + def psi2s_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['psi2s_mass'], 2)) * resonance(q, _mass = self.params['psi2s_mass'], + scale = self.params['psi2s_scale'], + phase = self.params['psi2s_phase'], + width = self.params['psi2s_width']) + def p3770_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p3770_mass'], 2)) * resonance(q, _mass = self.params['p3770_mass'], + scale = self.params['p3770_scale'], + phase = self.params['p3770_phase'], + width = self.params['p3770_width']) + + def p4040_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4040_mass'], 2)) * resonance(q, _mass = self.params['p4040_mass'], + scale = self.params['p4040_scale'], + phase = self.params['p4040_phase'], + width = self.params['p4040_width']) + + def p4160_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4160_mass'], 2)) * resonance(q, _mass = self.params['p4160_mass'], + scale = self.params['p4160_scale'], + phase = self.params['p4160_phase'], + width = self.params['p4160_width']) + + def p4415_res(q): + return ztf.to_complex(tf.pow(q, 2) / tf.pow(self.params['p4415_mass'], 2)) * resonance(q, _mass = self.params['p4415_mass'], + scale = self.params['p4415_scale'], + phase = self.params['p4415_phase'], + width = self.params['p4415_width']) + + def P2_D(q): + 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)) + 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))) + return Dbar_contrib + DDstar_contrib + + def ttau_cusp(q): + 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))) + + + 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) + + vec_f = vec(x, funcs, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + axiv_nr = axiv_nonres(x, b0_0, b0_1, b0_2, bplus_0, bplus_1, bplus_2, bT_0, bT_1, bT_2) + + tot = vec_f + axiv_nr + + #Cut out jpsi and psi2s + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(jpsi_mass-60.), x > ztf.constant(jpsi_mass+70.)), tot, 0.0*tot) + +# tot = tf.where(tf.math.logical_or(x < ztf.constant(psi2s_mass-50.), x > ztf.constant(psi2s_mass+50.)), tot, 0.0*tot) + + return tot + + +# ## Setup parameters + +# In[6]: + + +# formfactors + +b0_0 = zfit.Parameter("b0_0", ztf.constant(0.292), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_1 = zfit.Parameter("b0_1", ztf.constant(0.281), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +b0_2 = zfit.Parameter("b0_2", ztf.constant(0.150), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + +bplus_0 = zfit.Parameter("bplus_0", ztf.constant(0.466), lower_limit = -2.0, upper_limit= 2.0) +bplus_1 = zfit.Parameter("bplus_1", ztf.constant(-0.885), lower_limit = -2.0, upper_limit= 2.0) +bplus_2 = zfit.Parameter("bplus_2", ztf.constant(-0.213), lower_limit = -2.0, upper_limit= 2.0) + +bT_0 = zfit.Parameter("bT_0", ztf.constant(0.460), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_1 = zfit.Parameter("bT_1", ztf.constant(-1.089), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) +bT_2 = zfit.Parameter("bT_2", ztf.constant(-1.114), floating = False) #, lower_limit = -2.0, upper_limit= 2.0) + + +#rho + +rho_mass, rho_width, rho_phase, rho_scale = pdg["rho"] + +rho_m = zfit.Parameter("rho_m", ztf.constant(rho_mass), floating = False) #lower_limit = rho_mass - rho_width, upper_limit = rho_mass + rho_width) +rho_w = zfit.Parameter("rho_w", ztf.constant(rho_width), floating = False) +rho_p = zfit.Parameter("rho_p", ztf.constant(rho_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#omega + +omega_mass, omega_width, omega_phase, omega_scale = pdg["omega"] + +omega_m = zfit.Parameter("omega_m", ztf.constant(omega_mass), floating = False) +omega_w = zfit.Parameter("omega_w", ztf.constant(omega_width), floating = False) +omega_p = zfit.Parameter("omega_p", ztf.constant(omega_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +#phi + +phi_mass, phi_width, phi_phase, phi_scale = pdg["phi"] + +phi_m = zfit.Parameter("phi_m", ztf.constant(phi_mass), floating = False) +phi_w = zfit.Parameter("phi_w", ztf.constant(phi_width), floating = False) +phi_p = zfit.Parameter("phi_p", ztf.constant(phi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#jpsi + +jpsi_mass, jpsi_width, jpsi_phase, jpsi_scale = pdg["jpsi"] + +jpsi_m = zfit.Parameter("jpsi_m", ztf.constant(jpsi_mass), floating = False) +jpsi_w = zfit.Parameter("jpsi_w", ztf.constant(jpsi_width), floating = False) +jpsi_p = zfit.Parameter("jpsi_p", ztf.constant(jpsi_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi2s + +psi2s_mass, psi2s_width, psi2s_phase, psi2s_scale = pdg["psi2s"] + +psi2s_m = zfit.Parameter("psi2s_m", ztf.constant(psi2s_mass), floating = False) +psi2s_w = zfit.Parameter("psi2s_w", ztf.constant(psi2s_width), floating = False) +psi2s_p = zfit.Parameter("psi2s_p", ztf.constant(psi2s_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(3770) + +p3770_mass, p3770_width, p3770_phase, p3770_scale = pdg["p3770"] + +p3770_m = zfit.Parameter("p3770_m", ztf.constant(p3770_mass), floating = False) +p3770_w = zfit.Parameter("p3770_w", ztf.constant(p3770_width), floating = False) +p3770_p = zfit.Parameter("p3770_p", ztf.constant(p3770_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4040) + +p4040_mass, p4040_width, p4040_phase, p4040_scale = pdg["p4040"] + +p4040_m = zfit.Parameter("p4040_m", ztf.constant(p4040_mass), floating = False) +p4040_w = zfit.Parameter("p4040_w", ztf.constant(p4040_width), floating = False) +p4040_p = zfit.Parameter("p4040_p", ztf.constant(p4040_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4160) + +p4160_mass, p4160_width, p4160_phase, p4160_scale = pdg["p4160"] + +p4160_m = zfit.Parameter("p4160_m", ztf.constant(p4160_mass), floating = False) +p4160_w = zfit.Parameter("p4160_w", ztf.constant(p4160_width), floating = False) +p4160_p = zfit.Parameter("p4160_p", ztf.constant(p4160_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + +#psi(4415) + +p4415_mass, p4415_width, p4415_phase, p4415_scale = pdg["p4415"] + +p4415_m = zfit.Parameter("p4415_m", ztf.constant(p4415_mass), floating = False) +p4415_w = zfit.Parameter("p4415_w", ztf.constant(p4415_width), floating = False) +p4415_p = zfit.Parameter("p4415_p", ztf.constant(p4415_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi) +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)) + + +# ## Dynamic generation of 2 particle contribution + +# In[7]: + + +m_c = 1300 + +Dbar_phase = 0.0 +DDstar_phase = 0.0 +Dstar_mass = pdg['Dst_M'] +Dbar_mass = pdg['D0_M'] +D_mass = pdg['D0_M'] + +Dbar_s = zfit.Parameter("Dbar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3) +Dbar_m = zfit.Parameter("Dbar_m", ztf.constant(Dbar_mass), floating = False) +Dbar_p = zfit.Parameter("Dbar_p", ztf.constant(Dbar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) +DDstar_s = zfit.Parameter("DDstar_s", ztf.constant(0.0), lower_limit=-0.3, upper_limit=0.3)#, floating = False) +Dstar_m = zfit.Parameter("Dstar_m", ztf.constant(Dstar_mass), floating = False) +D_m = zfit.Parameter("D_m", ztf.constant(D_mass), floating = False) +DDstar_p = zfit.Parameter("DDstar_p", ztf.constant(DDstar_phase), lower_limit=-2*np.pi, upper_limit=2*np.pi)#, floating = False) + + +# ## Tau parameters + +# In[8]: + + +tau_m = zfit.Parameter("tau_m", ztf.constant(pdg['tau_M']), floating = False) +Ctt = zfit.Parameter("Ctt", ztf.constant(0.0), lower_limit=-0.5, upper_limit=0.5) + + +# ## Load data + +# In[9]: + + +x_min = 2*pdg['muon_M'] +x_max = (pdg["Bplus_M"]-pdg["Ks_M"]-0.1) + +# # Full spectrum + +obs_toy = zfit.Space('q', limits = (x_min, x_max)) + +# Jpsi and Psi2s cut out + +obs1 = zfit.Space('q', limits = (x_min, jpsi_mass - 60.)) +obs2 = zfit.Space('q', limits = (jpsi_mass + 70., psi2s_mass - 50.)) +obs3 = zfit.Space('q', limits = (psi2s_mass + 50., x_max)) + +obs_fit = obs1 + obs2 + obs3 + +# 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: +# part_set = pkl.load(input_file) + +# x_part = part_set['x_part'] + +# x_part = x_part.astype('float64') + +# data = zfit.data.Data.from_numpy(array=x_part, obs=obs) + + +# ## Setup pdf + +# In[10]: + + +total_f = total_pdf_cut(obs=obs_toy, jpsi_mass = jpsi_m, jpsi_scale = jpsi_s, jpsi_phase = jpsi_p, jpsi_width = jpsi_w, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +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, + psi2s_mass = psi2s_m, psi2s_scale = psi2s_s, psi2s_phase = psi2s_p, psi2s_width = psi2s_w, + p3770_mass = p3770_m, p3770_scale = p3770_s, p3770_phase = p3770_p, p3770_width = p3770_w, + p4040_mass = p4040_m, p4040_scale = p4040_s, p4040_phase = p4040_p, p4040_width = p4040_w, + p4160_mass = p4160_m, p4160_scale = p4160_s, p4160_phase = p4160_p, p4160_width = p4160_w, + p4415_mass = p4415_m, p4415_scale = p4415_s, p4415_phase = p4415_p, p4415_width = p4415_w, + rho_mass = rho_m, rho_scale = rho_s, rho_phase = rho_p, rho_width = rho_w, + omega_mass = omega_m, omega_scale = omega_s, omega_phase = omega_p, omega_width = omega_w, + phi_mass = phi_m, phi_scale = phi_s, phi_phase = phi_p, phi_width = phi_w, + Dstar_mass = Dstar_m, DDstar_scale = DDstar_s, DDstar_phase = DDstar_p, D_mass = D_m, + Dbar_mass = Dbar_m, Dbar_scale = Dbar_s, Dbar_phase = Dbar_p, + tau_mass = tau_m, C_tt = Ctt, b0_0 = b0_0, b0_1 = b0_1, b0_2 = b0_2, + bplus_0 = bplus_0, bplus_1 = bplus_1, bplus_2 = bplus_2, + bT_0 = bT_0, bT_1 = bT_1, bT_2 = bT_2) + +# print(total_pdf.obs) + +# print(calcs_test) + +# for param in total_f.get_dependents(): +# print(zfit.run(param)) + + +# In[11]: + + +total_f_fit.normalization(obs_toy) + + +# ## Test if graphs actually work and compute values + +# In[12]: + + +# def total_test_tf(xq): + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# def psi2s_res(q): +# return resonance(q, psi2s_m, psi2s_s, psi2s_p, psi2s_w) + +# def cusp(q): +# return bifur_gauss(q, cusp_m, sig_L, sig_R, cusp_s) + +# funcs = jpsi_res(xq) + psi2s_res(xq) + cusp(xq) + +# vec_f = vec(xq, funcs) + +# axiv_nr = axiv_nonres(xq) + +# tot = vec_f + axiv_nr + +# return tot + +# def jpsi_res(q): +# return resonance(q, jpsi_m, jpsi_s, jpsi_p, jpsi_w) + +# calcs = zfit.run(total_test_tf(x_part)) + +test_q = np.linspace(x_min, x_max, int(2e6)) + +probs = total_f_fit.pdf(test_q, norm_range=False) + +calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) +# b0 = [b0_0, b0_1, b0_2] +# bplus = [bplus_0, bplus_1, bplus_2] +# bT = [bT_0, bT_1, bT_2] +# f0_y = zfit.run(tf.math.real(formfactor(test_q,"0", b0, bplus, bT))) +# fplus_y = zfit.run(tf.math.real(formfactor(test_q,"+", b0, bplus, bT))) +# fT_y = zfit.run(tf.math.real(formfactor(test_q,"T", b0, bplus, bT))) + + +# In[13]: + + +plt.clf() +# plt.plot(x_part, calcs, '.') +plt.plot(test_q, calcs_test, label = 'pdf') +# plt.plot(test_q, f0_y, label = '0') +# plt.plot(test_q, fT_y, label = 'T') +# plt.plot(test_q, fplus_y, label = '+') +# plt.plot(test_q, res_y, label = 'res') +plt.legend() +plt.ylim(0.0, 1.5e-6) +# plt.yscale('log') +# plt.xlim(770, 785) +plt.savefig('test.png') +# print(jpsi_width) + + +# In[14]: + + + + +# probs = mixture.prob(test_q) +# probs_np = zfit.run(probs) +# probs_np *= np.max(calcs_test) / np.max(probs_np) +# plt.figure() +# plt.semilogy(test_q, probs_np,label="importance sampling") +# plt.semilogy(test_q, calcs_test, label = 'pdf') + + +# In[15]: + + +# 0.213/(0.00133+0.213+0.015) + + +# ## Adjust scaling of different parts + +# In[16]: + + +total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# inte = total_f.integrate(limits = (950., 1050.), norm_range=False) +# inte_fl = zfit.run(inte) +# print(inte_fl/4500) +# print(pdg["jpsi_BR"]/pdg["NR_BR"], inte_fl*pdg["psi2s_auc"]/pdg["NR_auc"]) + + +# In[17]: + + +# # print("jpsi:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["jpsi"][3]*np.sqrt(pdg["jpsi_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# # print("psi2s:", inte_fl) +# # print("Increase am by factor:", np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# # print("New amp:", pdg["psi2s"][3]*np.sqrt(pdg["psi2s_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + +# name = "phi" + +# print(name+":", inte_fl) +# print("Increase am by factor:", np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) +# print("New amp:", pdg[name][0]*np.sqrt(pdg[name+"_BR"]/pdg["NR_BR"]*pdg["NR_auc"]/inte_fl)) + + +# print(x_min) +# print(x_max) +# # total_f.update_integration_options(draws_per_dim=2000000, mc_sampler=None) +# total_f.update_integration_options(mc_sampler=lambda dim, num_results, +# dtype: tf.random_uniform(maxval=1., shape=(num_results, dim), dtype=dtype), +# draws_per_dim=1000000) +# # _ = [] + +# # for i in range(10): + +# # inte = total_f.integrate(limits = (x_min, x_max)) +# # inte_fl = zfit.run(inte) +# # print(inte_fl) +# # _.append(inte_fl) + +# # print("mean:", np.mean(_)) + +# _ = time.time() + +# inte = total_f.integrate(limits = (x_min, x_max)) +# inte_fl = zfit.run(inte) +# print(inte_fl) +# print("Time taken: {}".format(display_time(int(time.time() - _)))) + +# print(pdg['NR_BR']/pdg['NR_auc']*inte_fl) +# print(0.25**2*4.2/1000) + + +# # Sampling +# ## Mixture distribution for sampling + +# In[18]: + + + + +# print(list_of_borders[:9]) +# print(list_of_borders[-9:]) + + +class UniformSampleAndWeights(zfit.util.execution.SessionHolderMixin): + def __call__(self, limits, dtype, n_to_produce): + # n_to_produce = tf.cast(n_to_produce, dtype=tf.int32) + low, high = limits.limit1d + low = tf.cast(low, dtype=dtype) + high = tf.cast(high, dtype=dtype) +# uniform = tfd.Uniform(low=low, high=high) +# uniformjpsi = tfd.Uniform(low=tf.constant(3080, dtype=dtype), high=tf.constant(3112, dtype=dtype)) +# uniformpsi2s = tfd.Uniform(low=tf.constant(3670, dtype=dtype), high=tf.constant(3702, dtype=dtype)) + +# list_of_borders = [] +# _p = [] +# splits = 10 + +# _ = np.linspace(x_min, x_max, splits) + +# for i in range(splits): +# list_of_borders.append(tf.constant(_[i], dtype=dtype)) +# _p.append(tf.constant(1/splits, dtype=dtype)) + +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=_p[:(splits-1)]), +# components_distribution=tfd.Uniform(low=list_of_borders[:(splits-1)], +# high=list_of_borders[-(splits-1):])) + mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.05, dtype=dtype), + tf.constant(0.93, dtype=dtype), + tf.constant(0.05, dtype=dtype), + tf.constant(0.065, dtype=dtype), + tf.constant(0.04, dtype=dtype), + tf.constant(0.05, dtype=dtype)]), + components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), + tf.constant(3090, dtype=dtype), + tf.constant(3681, dtype=dtype), + tf.constant(3070, dtype=dtype), + tf.constant(1000, dtype=dtype), + tf.constant(3660, dtype=dtype)], + high=[tf.constant(x_max, dtype=dtype), + tf.constant(3102, dtype=dtype), + tf.constant(3691, dtype=dtype), + tf.constant(3110, dtype=dtype), + tf.constant(1040, dtype=dtype), + tf.constant(3710, dtype=dtype)])) +# dtype = tf.float64 +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.04, dtype=dtype), +# tf.constant(0.90, dtype=dtype), +# tf.constant(0.02, dtype=dtype), +# tf.constant(0.07, dtype=dtype), +# tf.constant(0.02, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype)], +# high=[tf.constant(3089, dtype=dtype), +# tf.constant(3103, dtype=dtype), +# tf.constant(3681, dtype=dtype), +# tf.constant(3691, dtype=dtype), +# tf.constant(x_max, dtype=dtype)])) +# mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + sample = mixture.sample((n_to_produce, 1)) +# sample = tf.random.uniform((n_to_produce, 1), dtype=dtype) + weights = mixture.prob(sample)[:,0] +# weights = tf.broadcast_to(tf.constant(1., dtype=dtype), shape=(n_to_produce,)) + # sample = tf.expand_dims(sample, axis=-1) +# print(sample, weights) + +# weights = tf.ones(shape=(n_to_produce,), dtype=dtype) + weights_max = None + thresholds = tf.random_uniform(shape=(n_to_produce,), dtype=dtype) + return sample, thresholds, weights, weights_max, n_to_produce + + +# In[19]: + + +# total_f._sample_and_weights = UniformSampleAndWeights + + +# In[20]: + + +# 0.00133/(0.00133+0.213+0.015)*(x_max-3750)/(x_max-x_min) + + +# In[21]: + + +# zfit.settings.set_verbosity(10) + + +# In[22]: + + +# # zfit.run.numeric_checks = False + +# nr_of_toys = 1 +# nevents = int(pdg["number_of_decays"]) +# nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# # clear_output(wait=True) + +# c = call + 1 + +# print("{0}/{1} of Toy {2}/{3}".format(c, calls, toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + + +# In[23]: + + +# with open(r"data/zfit_toys/toy_0/0.pkl", "rb") as input_file: +# sam = pkl.load(input_file) +# print(sam[:10]) + +# with open(r"data/zfit_toys/toy_0/1.pkl", "rb") as input_file: +# sam2 = pkl.load(input_file) +# print(sam2[:10]) + +# print(np.sum(sam-sam2)) + + +# In[24]: + + +# print("Time to generate full toy: {} s".format(int(time.time()-start))) + +# total_samp = [] + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# data2 = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# data3 = zfit.data.Data.from_numpy(array=total_samp, obs=obs) + +# print(total_samp[:nevents].shape) + + +# In[25]: + + +# plt.clf() + +# bins = int((x_max-x_min)/7) + +# # calcs = zfit.run(total_test_tf(samp)) +# print(total_samp[:nevents].shape) + +# plt.hist(total_samp[:nevents], bins = bins, range = (x_min,x_max), label = 'data') +# # plt.plot(test_q, calcs_test*nevents , label = 'pdf') + +# # plt.plot(sam, calcs, '.') +# # plt.plot(test_q, calcs_test) +# # plt.yscale('log') +# plt.ylim(0, 200) +# # plt.xlim(3080, 3110) + +# plt.legend() + +# plt.savefig('test2.png') + + +# In[26]: + + +# sampler = total_f.create_sampler(n=nevents) +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=sampler, fit_range = (x_min, x_max)) + +# # for param in pdf.get_dependents(): +# # param.set_value(initial_value) + +# sampler.resample(n=nevents) + +# # Randomise initial values +# # for param in pdf.get_dependents(): +# # param.set_value(random value here) + +# # Minimise the NLL +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 10) +# minimum = minimizer.minimize(nll) + + +# In[27]: + + +# jpsi_width + + +# In[28]: + + +# plt.hist(sample, weights=1 / prob(sample)) + + +# # Fitting + +# In[29]: + + +# start = time.time() + +# for param in total_f.get_dependents(): +# param.randomize() + +# # for param in total_f.get_dependents(): +# # print(zfit.run(param)) + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data2, fit_range = (x_min, x_max)) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# # param_errors = result.error() + +# # for var, errors in param_errors.items(): +# # print('{}: ^{{+{}}}_{{{}}}'.format(var.name, errors['upper'], errors['lower'])) + +# print("Function minimum:", result.fmin) +# # print("Results:", result.params) +# print("Hesse errors:", result.hesse()) + + +# In[30]: + + +# print("Time taken for fitting: {}".format(display_time(int(time.time()-start)))) + +# # probs = total_f.pdf(test_q) + +# calcs_test = zfit.run(probs) +# res_y = zfit.run(jpsi_res(test_q)) + + +# In[31]: + + +# plt.clf() +# # plt.plot(x_part, calcs, '.') +# plt.plot(test_q, calcs_test, label = 'pdf') +# # plt.plot(test_q, res_y, label = 'res') +# plt.legend() +# plt.ylim(0.0, 10e-6) +# # plt.yscale('log') +# # plt.xlim(3080, 3110) +# plt.savefig('test3.png') +# # print(jpsi_width) + + +# In[32]: + + +# _tot = 4.37e-7+6.02e-5+4.97e-6 +# _probs = [] +# _probs.append(6.02e-5/_tot) +# _probs.append(4.97e-6/_tot) +# _probs.append(4.37e-7/_tot) +# print(_probs) + + +# In[33]: + + +# dtype = 'float64' +# # mixture = tfd.Uniform(tf.constant(x_min, dtype=dtype), tf.constant(x_max, dtype=dtype)) +# mixture = tfd.MixtureSameFamily(mixture_distribution=tfd.Categorical(probs=[tf.constant(0.007, dtype=dtype), +# tf.constant(0.917, dtype=dtype), +# tf.constant(0.076, dtype=dtype)]), +# components_distribution=tfd.Uniform(low=[tf.constant(x_min, dtype=dtype), +# tf.constant(3080, dtype=dtype), +# tf.constant(3670, dtype=dtype)], +# high=[tf.constant(x_max, dtype=dtype), +# tf.constant(3112, dtype=dtype), +# tf.constant(3702, dtype=dtype)])) +# # for i in range(10): +# # print(zfit.run(mixture.prob(mixture.sample((10, 1))))) + + +# In[34]: + + +# print((zfit.run(jpsi_p)%(2*np.pi))/np.pi) +# print((zfit.run(psi2s_p)%(2*np.pi))/np.pi) + + +# In[35]: + + +# def jpsi_res(q): +# return resonance(q, _mass = jpsi_mass, scale = jpsi_scale, +# phase = jpsi_phase, width = jpsi_width) + +# def psi2s_res(q): +# return resonance(q, _mass = psi2s_mass, scale = psi2s_scale, +# phase = psi2s_phase, width = psi2s_width) + +# def p3770_res(q): +# return resonance(q, _mass = p3770_mass, scale = p3770_scale, +# phase = p3770_phase, width = p3770_width) + +# def p4040_res(q): +# return resonance(q, _mass = p4040_mass, scale = p4040_scale, +# phase = p4040_phase, width = p4040_width) + +# def p4160_res(q): +# return resonance(q, _mass = p4160_mass, scale = p4160_scale, +# phase = p4160_phase, width = p4160_width) + +# def p4415_res(q): +# return resonance(q, _mass = p4415_mass, scale = p4415_scale, +# phase = p4415_phase, width = p4415_width) + + +# In[36]: + + +# 0.15**2*4.2/1000 +# result.hesse() + + +# ## Constraints + +# In[37]: + + +# 1. Constraint - Real part of sum of Psi contrib and D contribs + +sum_list = [] + +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)))) +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)))) +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)))) +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)))) +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)))) +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)))) +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))))) +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)))) + +sum_ru_1 = ztf.to_complex(ztf.constant(0.0)) + +for part in sum_list: + sum_ru_1 += part + +sum_1 = tf.math.real(sum_ru_1) +# constraint1 = zfit.constraint.GaussianConstraint(params = sum_1, mu = ztf.constant(1.7*10**-8), +# sigma = ztf.constant(2.2*10**-8)) + +constraint1 = tf.pow((sum_1-ztf.constant(1.7*10**-8))/ztf.constant(2.2*10**-8),2)/ztf.constant(2.) + +# 2. Constraint - Abs. of sum of Psi contribs and D contribs + +sum_2 = tf.abs(sum_ru_1) +constraint2 = tf.cond(tf.greater_equal(sum_2, 5.0e-8), lambda: 100000., lambda: 0.) + +# 3. Constraint - Maximum eta of D contribs + +constraint3_0 = tf.cond(tf.greater_equal(tf.abs(Dbar_s), 0.2), lambda: 100000., lambda: 0.) + +constraint3_1 = tf.cond(tf.greater_equal(tf.abs(DDstar_s), 0.2), lambda: 100000., lambda: 0.) + +# 4. Constraint - Formfactor multivariant gaussian covariance fplus + +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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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)], + [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.)]] + +def triGauss(val1,val2,val3,m = Cov_matrix): + + mean1 = ztf.constant(0.466) + mean2 = ztf.constant(-0.885) + mean3 = ztf.constant(-0.213) + sigma1 = ztf.constant(0.014) + sigma2 = ztf.constant(0.128) + sigma3 = ztf.constant(0.548) + x1 = (val1-mean1)/sigma1 + x2 = (val2-mean2)/sigma2 + x3 = (val3-mean3)/sigma3 + rho12 = m[0][1] + rho13 = m[0][2] + rho23 = m[1][2] + 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)) + d = 2*(rho12*rho12+rho13*rho13+rho23*rho23-2*rho12*rho13*rho23-1) + + fcn = -w/d + chisq = -2*fcn + return chisq + +constraint4 = triGauss(bplus_0, bplus_1, bplus_2) + +# mean1 = ztf.constant(0.466) +# mean2 = ztf.constant(-0.885) +# mean3 = ztf.constant(-0.213) +# sigma1 = ztf.constant(0.014) +# sigma2 = ztf.constant(0.128) +# sigma3 = ztf.constant(0.548) +# constraint4_0 = tf.pow((bplus_0-mean1)/sigma1,2)/ztf.constant(2.) +# constraint4_1 = tf.pow((bplus_1-mean2)/sigma2,2)/ztf.constant(2.) +# constraint4_2 = tf.pow((bplus_2-mean3)/sigma3,2)/ztf.constant(2.) + +# 5. Constraint - Abs. of sum of light contribs + +sum_list_5 = [] + +sum_list_5.append(rho_s*rho_w/rho_m) +sum_list_5.append(omega_s*omega_w/omega_m) +sum_list_5.append(phi_s*phi_w/phi_m) + + +sum_ru_5 = ztf.constant(0.0) + +for part in sum_list_5: + sum_ru_5 += part + +constraint5 = tf.cond(tf.greater_equal(tf.abs(sum_ru_5), ztf.constant(0.02)), lambda: 100000., lambda: 0.) + +# 6. Constraint on phases of Jpsi and Psi2s for cut out fit + + +# constraint6_0 = zfit.constraint.GaussianConstraint(params = jpsi_p, mu = ztf.constant(pdg["jpsi_phase_unc"]), +# sigma = ztf.constant(jpsi_phase)) +# constraint6_1 = zfit.constraint.GaussianConstraint(params = psi2s_p, mu = ztf.constant(pdg["psi2s_phase_unc"]), +# sigma = ztf.constant(psi2s_phase)) + +constraint6_0 = tf.pow((jpsi_p-ztf.constant(jpsi_phase))/ztf.constant(pdg["jpsi_phase_unc"]),2)/ztf.constant(2.) +constraint6_1 = tf.pow((psi2s_p-ztf.constant(psi2s_phase))/ztf.constant(pdg["psi2s_phase_unc"]),2)/ztf.constant(2.) + +# 7. Constraint on Ctt with higher limits + +constraint7 = tf.cond(tf.greater_equal(Ctt*Ctt, 0.25), lambda: 100000., lambda: 0.) + +constraint7dtype = tf.float64 + +# zfit.run(constraint6_0) + +# ztf.convert_to_tensor(constraint6_0) + +#List of all constraints + +constraints = [constraint1, constraint2, constraint3_0, constraint3_1,# constraint4, #constraint4_0, constraint4_1, constraint4_2, + constraint6_0, constraint6_1]#, constraint7] + + +# ## Reset params + +# In[38]: + + +def reset_param_values(): + jpsi_m.set_value(jpsi_mass) + jpsi_s.set_value(jpsi_scale) + jpsi_p.set_value(jpsi_phase) + jpsi_w.set_value(jpsi_width) + psi2s_m.set_value(psi2s_mass) + psi2s_s.set_value(psi2s_scale) + psi2s_p.set_value(psi2s_phase) + psi2s_w.set_value(psi2s_width) + p3770_m.set_value(p3770_mass) + p3770_s.set_value(p3770_scale) + p3770_p.set_value(p3770_phase) + p3770_w.set_value(p3770_width) + p4040_m.set_value(p4040_mass) + p4040_s.set_value(p4040_scale) + p4040_p.set_value(p4040_phase) + p4040_w.set_value(p4040_width) + p4160_m.set_value(p4160_mass) + p4160_s.set_value(p4160_scale) + p4160_p.set_value(p4160_phase) + p4160_w.set_value(p4160_width) + p4415_m.set_value(p4415_mass) + p4415_s.set_value(p4415_scale) + p4415_p.set_value(p4415_phase) + p4415_w.set_value(p4415_width) + rho_m.set_value(rho_mass) + rho_s.set_value(rho_scale) + rho_p.set_value(rho_phase) + rho_w.set_value(rho_width) + omega_m.set_value(omega_mass) + omega_s.set_value(omega_scale) + omega_p.set_value(omega_phase) + omega_w.set_value(omega_width) + phi_m.set_value(phi_mass) + phi_s.set_value(phi_scale) + phi_p.set_value(phi_phase) + phi_w.set_value(phi_width) + Dstar_m.set_value(Dstar_mass) + DDstar_s.set_value(0.0) + DDstar_p.set_value(0.0) + D_m.set_value(D_mass) + Dbar_m.set_value(Dbar_mass) + Dbar_s.set_value(0.0) + Dbar_p.set_value(0.0) + tau_m.set_value(pdg['tau_M']) + Ctt.set_value(0.0) + b0_0.set_value(0.292) + b0_1.set_value(0.281) + b0_2.set_value(0.150) + bplus_0.set_value(0.466) + bplus_1.set_value(-0.885) + bplus_2.set_value(-0.213) + bT_0.set_value(0.460) + bT_1.set_value(-1.089) + bT_2.set_value(-1.114) + + +# # Analysis + +# In[39]: + + +# # zfit.run.numeric_checks = False + +# fitting_range = 'cut' +# 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 +# cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +# Ctt_list = [] +# Ctt_error_list = [] + +# nr_of_toys = 1 +# if fitting_range == 'cut': +# nevents = int(pdg["number_of_decays"]*cut_BR) +# else: +# nevents = int(pdg["number_of_decays"]) +# # nevents = pdg["number_of_decays"] +# event_stack = 1000000 +# # nevents *= 41 +# # zfit.settings.set_verbosity(10) +# calls = int(nevents/event_stack + 1) + +# total_samp = [] + +# start = time.time() + +# sampler = total_f.create_sampler(n=event_stack) + +# for toy in range(nr_of_toys): + +# ### Generate data + +# # clear_output(wait=True) + +# print("Toy {}: Generating data...".format(toy)) + +# dirName = 'data/zfit_toys/toy_{0}'.format(toy) + +# if not os.path.exists(dirName): +# os.mkdir(dirName) +# print("Directory " , dirName , " Created ") + +# reset_param_values() + +# if fitting_range == 'cut': + +# sampler.resample(n=nevents) +# s = sampler.unstack_x() +# sam = zfit.run(s) +# calls = 0 +# c = 1 + +# else: +# for call in range(calls): + +# sampler.resample(n=event_stack) +# s = sampler.unstack_x() +# sam = zfit.run(s) + +# c = call + 1 + +# with open("data/zfit_toys/toy_{0}/{1}.pkl".format(toy, call), "wb") as f: +# pkl.dump(sam, f, pkl.HIGHEST_PROTOCOL) + +# print("Toy {}: Data generation finished".format(toy)) + +# ### Load data + +# print("Toy {}: Loading data...".format(toy)) + +# if fitting_range == 'cut': + +# total_samp = sam + +# else: + +# for call in range(calls): +# with open(r"data/zfit_toys/toy_0/{}.pkl".format(call), "rb") as input_file: +# sam = pkl.load(input_file) +# total_samp = np.append(total_samp, sam) + +# total_samp = total_samp.astype('float64') + +# if fitting_range == 'full': + +# data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f, data=data, fit_range = (x_min, x_max), constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Toy {}: Fitting finished".format(toy)) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# probs = total_f.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.legend() +# plt.ylim(0.0, 6e-6) +# plt.savefig(plotdirName + '/toy_fit_full_range{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(c+calls*(toy))*((nr_of_toys-toy)*calls-c))))) + +# if fitting_range == 'cut': + +# _1 = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 60.))) + +# tot_sam_1 = total_samp[_1] + +# _2 = np.where((total_samp >= (jpsi_mass + 70.)) & (total_samp <= (psi2s_mass - 50.))) + +# tot_sam_2 = total_samp[_2] + +# _3 = np.where((total_samp >= (psi2s_mass + 50.)) & (total_samp <= x_max)) + +# tot_sam_3 = total_samp[_3] + +# tot_sam = np.append(tot_sam_1, tot_sam_2) +# tot_sam = np.append(tot_sam, tot_sam_3) + +# data = zfit.data.Data.from_numpy(array=tot_sam[:int(nevents)], obs=obs_fit) + +# print("Toy {}: Loading data finished".format(toy)) + +# ### Fit data + +# print("Toy {}: Fitting pdf...".format(toy)) + +# for param in total_f_fit.get_dependents(): +# param.randomize() + +# nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + +# minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) +# # minimizer._use_tfgrad = False +# result = minimizer.minimize(nll) + +# print("Function minimum:", result.fmin) +# print("Hesse errors:", result.hesse()) + +# params = result.params + +# if result.converged: +# Ctt_list.append(params[Ctt]['value']) +# Ctt_error_list.append(params[Ctt]['minuit_hesse']['error']) + +# #plotting the result + +# plotdirName = 'data/plots'.format(toy) + +# if not os.path.exists(plotdirName): +# os.mkdir(plotdirName) +# # print("Directory " , dirName , " Created ") + +# plt.clf() +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.), label = 'toy data') +# plt.savefig(plotdirName + '/toy_histo_cut_region{}.png'.format(toy)) + + +# probs = total_f_fit.pdf(test_q, norm_range=False) +# calcs_test = zfit.run(probs) +# plt.clf() +# plt.plot(test_q, calcs_test, label = 'pdf') +# plt.axvline(x=jpsi_mass-60.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=jpsi_mass+70.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass-50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.axvline(x=psi2s_mass+50.,color='red', linewidth=0.7, linestyle = 'dotted') +# plt.legend() +# plt.ylim(0.0, 1.5e-6) +# plt.savefig(plotdirName + '/toy_fit_cut_region{}.png'.format(toy)) + +# print("Toy {0}/{1}".format(toy+1, nr_of_toys)) +# print("Time taken: {}".format(display_time(int(time.time() - start)))) +# print("Projected time left: {}".format(display_time(int((time.time() - start)/(toy+1))*((nr_of_toys-toy-1))))) + + + +# In[40]: + + +# with open("data/results/Ctt_list.pkl", "wb") as f: +# pkl.dump(Ctt_list, f, pkl.HIGHEST_PROTOCOL) +# with open("data/results/Ctt_error_list.pkl", "wb") as f: +# pkl.dump(Ctt_error_list, f, pkl.HIGHEST_PROTOCOL) + + +# In[41]: + + +# print('{0}/{1} fits converged'.format(len(Ctt_list), nr_of_toys)) +# print('Mean Ctt value = {}'.format(np.mean(Ctt_list))) +# print('Mean Ctt error = {}'.format(np.mean(Ctt_error_list))) +# print('95 Sensitivy = {}'.format(((2*np.mean(Ctt_error_list))**2)*4.2/1000)) + + +# In[42]: + + +# plt.hist(tot_sam, bins = int((x_max-x_min)/7.)) + +# plt.show() + +# # _ = np.where((total_samp >= x_min) & (total_samp <= (jpsi_mass - 50.))) + +# tot_sam.shape + + +# In[43]: + + +# Ctt.floating = False + + +# In[44]: + + +# zfit.run(nll.value()) + + +# In[45]: + + +# result.fmin + + +# In[46]: + + +# BR_steps = np.linspace(0.0, 1e-3, 11) + + +# # CLS Code + +# In[48]: + + +# zfit.run.numeric_checks = False + +load = False + +bo5 = True + +bo5_set = 5 + +fitting_range = 'cut' +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 +cut_BR = 1.0 - (6.02e-5 + 4.97e-6)/total_BR + +Ctt_list = [] +Ctt_error_list = [] + +nr_of_toys = 1 +nevents = int(pdg["number_of_decays"]*cut_BR) +# nevents = pdg["number_of_decays"] +event_stack = 1000000 +# nevents *= 41 +# zfit.settings.set_verbosity(10) + +mi = 0.0 +ma = 1e-3 +ste = 11 + +BR_steps = np.linspace(mi, ma, ste) + +Ctt_steps = np.sqrt(BR_steps/4.2*1000) + +total_samp = [] + +start = time.time() + +Nll_list = [] + +sampler = total_f.create_sampler(n=nevents) + +__ = 0 + +#----------------------------------------------------- + +if not load: + + for Ctt_step in Ctt_steps: + + __ += 1 + + newset = True + + for floaty in [True, False]: + + Ctt.floating = floaty + + Nll_list.append([]) + + if bo5: + + if __ < 6: + + while len(Nll_list[-1])/bo5_set < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1} - Fit {2}/{3}'.format(int(len(Nll_list[-1])/bo5_set), nr_of_toys, len(Nll_list[-1]), bo5_set)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if newset: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + newset = False + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + else: + + while len(Nll_list[-1]) < nr_of_toys: + + print('Step: {0}/{1}'.format(__, ste)) + + print('Current Ctt: {0}'.format(Ctt_step)) + print('Ctt floating: {0}'.format(floaty)) + + print('Toy {0}/{1}'.format(len(Nll_list[-1]), nr_of_toys)) + + reset_param_values() + + if floaty: + Ctt.set_value(Ctt_step) + else: + Ctt.set_value(0.0) + + if floaty: + sampler.resample(n=nevents) + s = sampler.unstack_x() + total_samp = zfit.run(s) + calls = 0 + c = 1 + + + data = zfit.data.Data.from_numpy(array=total_samp[:int(nevents)], obs=obs_fit) + + ### Fit data + + for param in total_f_fit.get_dependents(): + param.randomize() + + nll = zfit.loss.UnbinnedNLL(model=total_f_fit, data=data, constraints = constraints) + + minimizer = zfit.minimize.MinuitMinimizer(verbosity = 5) + # minimizer._use_tfgrad = False + result = minimizer.minimize(nll) + + # print("Function minimum:", result.fmin) + # print("Hesse errors:", result.hesse()) + + params = result.params + + if result.converged: + Nll_list[-1].append(result.fmin) + + _t = int(time.time()-start) + + print('Time Taken: {}'.format(display_time(int(_t)))) + + print('Predicted time left: {}'.format(display_time(int((_t/(__+1)*(ste-__-1)))))) + + +# In[49]: + + +if load: + Nll_list = [] + CLs_values = [] + + _dir = 'data/CLs/finished/f1d1' + + jobs = os.listdir(_dir) + + for s in range(ste): + CLs_values.append([]) + + for s in range(2*ste): + Nll_list.append([]) + + for job in jobs: + if not os.path.exists("{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste)): + print(job) + continue + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _Nll_list = pkl.load(input_file) + + if bo5: + for s in range(2*ste): + Nll_list[s].append(np.min(_Nll_list[s])) + else: + for s in range(2*ste): + Nll_list[s].extend(_Nll_list[s]) + + with open(r"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl".format(_dir, job, mi,ma,ste), "rb") as input_file: + _CLs_values = pkl.load(input_file) + + for s in range(ste): + CLs_values[s].extend(_CLs_values[s]) + + print(np.shape(Nll_list)) + + +# In[50]: + + +dirName = 'data/CLs' + +# if bo5 and not load: +# for s in range(2*ste): +# Nll_list[s] = [np.min(Nll_list[s])] + +# if bo5: +# CLs_values= [] +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(len(Nll_list[0])): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + + +if not load: + + if not os.path.exists(dirName): + os.mkdir(dirName) + print("Directory " , dirName , " Created ") + + with open("{}/{}-{}_{}s--CLs_Nll_list.pkl".format(dirName, mi,ma,ste), "wb") as f: + pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL) + +# CLs_values = [] + +# for i in range(int(len(Nll_list)/2)): +# CLs_values.append([]) +# for j in range(nr_of_toys): +# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j]) + +# with open("{}/{}-{}_{}s--CLs_list.pkl".format(dirName, mi,ma,ste), "wb") as f: +# pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL) + + +# In[51]: + + +# print(CLs_values) +# print(Nll_list) + + +# ## Plot + +# In[56]: + + +# l = [] + +# if not os.path.exists('data/CLs/plots'): +# os.mkdir('data/CLs/plots') +# print("Directory " , 'data/CLs/plots' , " Created ") + +# for i in range(len(CLs_values)): +# plt.clf() +# plt.title('Ctt value: {:.2f}'.format(Ctt_steps[i])) +# plt.hist(CLs_values[0], bins = 100, range = (-25, 25), label = 'Ctt fixed to 0') +# plt.hist(CLs_values[i], bins = 100, range = (-25, 25), label = 'Ctt floating') +# plt.axvline(x=np.mean(CLs_values[0]),color='red', linewidth=1.0, linestyle = 'dotted') +# plt.legend() +# plt.savefig('data/CLs/plots/CLs-BR({:.1E}).png'.format(BR_steps[i])) + +# l.append(len(np.where(np.array(CLs_values[i]) < np.mean(CLs_values[0]))[0])) + + +# In[57]: + + +# for s in range(len(l)): +# print('BR: {:.4f}'.format(BR_steps[s])) +# print(2*l[s]/len(CLs_values[0])) +# print() + + +# In[ ]: + + +# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10])) + + +# In[ ]: + + + + diff --git a/data/CLs/finished/f1d1/bo5-+/2257236/test.png b/data/CLs/finished/f1d1/bo5-+/2257236/test.png new file mode 100644 index 0000000..1455457 --- /dev/null +++ b/data/CLs/finished/f1d1/bo5-+/2257236/test.png Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0500.0E+00\051.png" "b/data/CLs/plots/CLs-BR\0500.0E+00\051.png" index 01d64f6..0e81b19 100644 --- "a/data/CLs/plots/CLs-BR\0500.0E+00\051.png" +++ "b/data/CLs/plots/CLs-BR\0500.0E+00\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0501.0E-03\051.png" "b/data/CLs/plots/CLs-BR\0501.0E-03\051.png" index 87b41c9..7671477 100644 --- "a/data/CLs/plots/CLs-BR\0501.0E-03\051.png" +++ "b/data/CLs/plots/CLs-BR\0501.0E-03\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0501.0E-04\051.png" "b/data/CLs/plots/CLs-BR\0501.0E-04\051.png" index a01c16a..fa0d668 100644 --- "a/data/CLs/plots/CLs-BR\0501.0E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0501.0E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0502.0E-04\051.png" "b/data/CLs/plots/CLs-BR\0502.0E-04\051.png" index f7ccf1a..4df5441 100644 --- "a/data/CLs/plots/CLs-BR\0502.0E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0502.0E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0503.0E-04\051.png" "b/data/CLs/plots/CLs-BR\0503.0E-04\051.png" index 139b1e4..e0279fc 100644 --- "a/data/CLs/plots/CLs-BR\0503.0E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0503.0E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0504.0E-04\051.png" "b/data/CLs/plots/CLs-BR\0504.0E-04\051.png" index f2d333c..28047f4 100644 --- "a/data/CLs/plots/CLs-BR\0504.0E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0504.0E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0505.0E-04\051.png" "b/data/CLs/plots/CLs-BR\0505.0E-04\051.png" index 5a3f99e..cf79f56 100644 --- "a/data/CLs/plots/CLs-BR\0505.0E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0505.0E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0506.0E-04\051.png" "b/data/CLs/plots/CLs-BR\0506.0E-04\051.png" index 9943f52..0f303e9 100644 --- "a/data/CLs/plots/CLs-BR\0506.0E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0506.0E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0507.0E-04\051.png" "b/data/CLs/plots/CLs-BR\0507.0E-04\051.png" index 7945903..2af9860 100644 --- "a/data/CLs/plots/CLs-BR\0507.0E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0507.0E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0508.0E-04\051.png" "b/data/CLs/plots/CLs-BR\0508.0E-04\051.png" index 4ffe10c..d9577e3 100644 --- "a/data/CLs/plots/CLs-BR\0508.0E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0508.0E-04\051.png" Binary files differ diff --git "a/data/CLs/plots/CLs-BR\0509.0E-04\051.png" "b/data/CLs/plots/CLs-BR\0509.0E-04\051.png" index afedc52..c247c80 100644 --- "a/data/CLs/plots/CLs-BR\0509.0E-04\051.png" +++ "b/data/CLs/plots/CLs-BR\0509.0E-04\051.png" Binary files differ diff --git a/pdg_const.py b/pdg_const.py index 6645dd7..eb24671 100644 --- a/pdg_const.py +++ b/pdg_const.py @@ -95,27 +95,27 @@ # after scaling (Phase combination --) -# "rho": (743.2, 149.0, -0.22, 1.05), + "rho": (743.2, 149.0, -0.22, 1.05), -# "omega": (782.7, 8.5, 0.38, 6.8), + "omega": (782.7, 8.5, 0.38, 6.8), -# "phi": (1013.5, 4.25, 0.62, 19.2), + "phi": (1013.5, 4.25, 0.62, 19.2), -# "jpsi": (3096.1, 0.09, 1.63, 9897.0), -# "jpsi_auc": 0.2126825758464027, -# "jpsi_phase_unc": 0.05, + "jpsi": (3096.1, 0.09, 1.63, 9897.0), + "jpsi_auc": 0.2126825758464027, + "jpsi_phase_unc": 0.05, -# "psi2s": (3686.0, 0.3, 1.8, 1396.0), -# "psi2s_auc": 0.0151332263, -# "psi2s_phase_unc": 0.1, + "psi2s": (3686.0, 0.3, 1.8, 1396.0), + "psi2s_auc": 0.0151332263, + "psi2s_phase_unc": 0.1, -# "p3770": (3773.0, 27.2, -2.95, 2.5), + "p3770": (3773.0, 27.2, -2.95, 2.5), -# "p4040": (4039.0, 80.0, -2.75, 1.01), + "p4040": (4039.0, 80.0, -2.75, 1.01), -# "p4160": (4191.0, 70.0, -2.28, 2.2), + "p4160": (4191.0, 70.0, -2.28, 2.2), -# "p4415": (4421.0, 62.0, -2.31, 1.24), + "p4415": (4421.0, 62.0, -2.31, 1.24), # Phase combination of paper ++ @@ -143,51 +143,51 @@ # Phase combination of paper +- - # "rho": (743.2, 149.0, -0.26, 1.05), - # - # "omega": (782.7, 8.5, 0.35, 6.8), - # - # "phi": (1013.5, 4.25, 0.58, 19.2), - # - # "jpsi": (3096.1, 0.09, 1.47, 9897.0), - # "jpsi_auc": 0.2126825758464027, - # "jpsi_phase_unc": 0.05, - # - # "psi2s": (3686.0, 0.3, -2.21, 1396.0), - # "psi2s_auc": 0.0151332263, - # "psi2s_phase_unc": 0.1, - # - # "p3770": (3773.0, 27.2, -2.140, 2.5), - # - # "p4040": (4039.0, 80.0, -2.64, 1.01), - # - # "p4160": (4191.0, 70.0, -2.11, 2.2), - # - # "p4415": (4421.0, 62.0, -2.42, 1.24), +# "rho": (743.2, 149.0, -0.26, 1.05), + +# "omega": (782.7, 8.5, 0.35, 6.8), + +# "phi": (1013.5, 4.25, 0.58, 19.2), + +# "jpsi": (3096.1, 0.09, 1.47, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, + +# "psi2s": (3686.0, 0.3, -2.21, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, + +# "p3770": (3773.0, 27.2, -2.140, 2.5), + +# "p4040": (4039.0, 80.0, -2.64, 1.01), + +# "p4160": (4191.0, 70.0, -2.11, 2.2), + +# "p4415": (4421.0, 62.0, -2.42, 1.24), # Phase combination of paper -+ - "rho": (743.2, 149.0, -0.30, 1.05), +# "rho": (743.2, 149.0, -0.30, 1.05), - "omega": (782.7, 8.5, 0.30, 6.8), +# "omega": (782.7, 8.5, 0.30, 6.8), - "phi": (1013.5, 4.25, 0.51, 19.2), +# "phi": (1013.5, 4.25, 0.51, 19.2), - "jpsi": (3096.1, 0.09, -1.5, 9897.0), - "jpsi_auc": 0.2126825758464027, - "jpsi_phase_unc": 0.05, +# "jpsi": (3096.1, 0.09, -1.5, 9897.0), +# "jpsi_auc": 0.2126825758464027, +# "jpsi_phase_unc": 0.05, - "psi2s": (3686.0, 0.3, 2.08, 1396.0), - "psi2s_auc": 0.0151332263, - "psi2s_phase_unc": 0.1, +# "psi2s": (3686.0, 0.3, 2.08, 1396.0), +# "psi2s_auc": 0.0151332263, +# "psi2s_phase_unc": 0.1, - "p3770": (3773.0, 27.2, -2.89, 2.5), +# "p3770": (3773.0, 27.2, -2.89, 2.5), - "p4040": (4039.0, 80.0, -2.69, 1.01), +# "p4040": (4039.0, 80.0, -2.69, 1.01), - "p4160": (4191.0, 70.0, -2.13, 2.2), +# "p4160": (4191.0, 70.0, -2.13, 2.2), - "p4415": (4421.0, 62.0, -2.43, 1.24), +# "p4415": (4421.0, 62.0, -2.43, 1.24), # zeroing resonances diff --git a/raremodel-nb.ipynb b/raremodel-nb.ipynb index b2495bc..0605683 100644 --- a/raremodel-nb.ipynb +++ b/raremodel-nb.ipynb @@ -850,11 +850,19 @@ "\n", "# calcs = zfit.run(total_test_tf(x_part))\n", "\n", + "\n", + "\n", "test_q = np.linspace(x_min, x_max, int(2e6))\n", "\n", "probs = total_f_fit.pdf(test_q, norm_range=False)\n", "\n", "calcs_test = zfit.run(probs)\n", + "\n", + "Ctt.set_value(0.5)\n", + "\n", + "probs1 = total_f_fit.pdf(test_q, norm_range=False)\n", + "\n", + "calcs_test1 = zfit.run(probs)\n", "# res_y = zfit.run(jpsi_res(test_q))\n", "# b0 = [b0_0, b0_1, b0_2]\n", "# bplus = [bplus_0, bplus_1, bplus_2]\n", @@ -873,15 +881,15 @@ "name": "stderr", "output_type": "stream", "text": [ - "C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\ipykernel_launcher.py:12: UserWarning: Creating legend with loc=\"best\" can be slow with large amounts of data.\n", - " if sys.path[0] == '':\n", + "C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\ipykernel_launcher.py:13: UserWarning: Creating legend with loc=\"best\" can be slow with large amounts of data.\n", + " del sys.path[0]\n", "C:\\Users\\sa_li\\.conda\\envs\\rmd\\lib\\site-packages\\IPython\\core\\pylabtools.py:128: UserWarning: Creating legend with loc=\"best\" can be slow with large amounts of data.\n", " fig.canvas.print_figure(bytes_io, **kw)\n" ] }, { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAaUAAAD4CAYAAABMtfkzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAgAElEQVR4nO29eXzc1XX3/z4zo9Eu2dq825JtGSMbsxmbHWM2k5CYJqRxElJSaMmTkrZJnjxNaJukTeH3lLZPaNKsvGISsmEoIcEhBIdgUwIYY4MNeMWyvMmbVkvWrpm5vz++d0bj0ayypBlJ5/16+eWZO/d77p2vre9H59xzzxVjDIqiKIqSCbjSPQFFURRFCaKipCiKomQMKkqKoihKxqCipCiKomQMKkqKoihKxuBJ9wQyjbKyMlNZWZnuaShKxrP35BkKsj3MnJx7Vvvprj6OtnazYEoh2Z70/t6781gbZYXZTC3KoaWzj2Onuzl/WhEel6R1XuORN998s8kYU36udlSUIqisrGTbtm3pnoaiZDzLHvwDKxdW8K8fXnJW+zM7jvG363bwqy9cx/yKgjTNzmHe3z/H/7puLv/nloX8YssR/v5X77Lh729gSlFOWuc1HhGRw8NhR8N3iqIMiYABVxSPw23bAhmwB9IYg0uc+QSn6g+kf15KbFSUFEUZEgFjiBYFc1sRyISHf8BAcIquDBJLJTYqSoqiDImAMSEBCifoKaVblILVaiTkKYltT9uUlCTQNSVFUYaEP2BCD/xwMkeUnL+DU0xX+K6/v5/6+np6enpGddyRIicnh5kzZ5KVlTUi9lWUFEUZEsYMCFA4wTCZP80uSXB0sQG8dK111dfXU1hYSGVlZVQRH0sYY2hubqa+vp6qqqoRGUPDd4qiDAl/IP6aUiDtnpIzfnCOQUEY7Wn19PRQWlo65gUJnHtYWlo6ol6fipKiKEMiYEzU7DtPhoTvAjHCd+lIdBgPghRkpL+LipKiKEMiEJZuHY4rQ0TJcHaiQ8iD00yHjEZFSVGUIeEPJMi+S/eaUoSnJBmUqp6JvPTSS9x2220A9Pb2cuONN3LRRRfxxBNPjOo8NNFBUZQhEWvzrCtDHv4hUYpIdFBHKTHbt2+nv7+fHTt2jPrYSXlKIrJKRPaJSK2IfDnK59ki8oT9fIuIVIZ9dr9t3ycitySyKSJV1sZ+a9MbbwwRKRWRTSLSISLfjjH/9SKyM7lboihKIoJJDNESHTwZskk1GL5zZcCaUro5dOgQCxcu5K677mLJkiXccccddHV18fzzz7Nw4UKuvvpqnn76aQAaGhq488472bFjBxdddBEHDhwY1bkm9JRExA18B7gJqAe2ish6Y8zusG73AK3GmPkisgZ4CPioiNQAa4BFwHTgDyKywF4Ty+ZDwMPGmHUi8n1r+3uxxgB6gK8Ai+2fyPl/COhI6a4oihKX4IM9XvjO58+0RIf0e3D//Jtd7D7ePqw2a6YX8bUPLErYb9++faxdu5arrrqKu+++m2984xv84Ac/YOPGjcyfP5+PfvSjAFRUVPDDH/6Q//iP/+DZZ58d1rkmQzKe0jKg1hhTZ4zpA9YBqyP6rAYes6+fAm4QJ4C7GlhnjOk1xhwEaq29qDbtNSutDazN2+ONYYzpNMa8giNOZyEiBcAXgAeS+J6KoiRJcL0oXvgu3R7JQEq4regQ8uDSNqW0MmvWLK666ioA7rzzTrZt20ZVVRXV1dWICHfeeWeaZ+iQzJrSDOBo2Pt6YHmsPsYYn4i0AaW2/fWIa2fY19FslgKnjTG+KP1jjdEUZ+7/Avw/oCveFxSRe4F7AWbPnh2vq6IoDKzLRMu+G6joMJozGkyk+AT106RRLJPxaEaKyFTutra2jExVT8ZTijbryH/VWH2Gqz3ZeQxMSOQiYL4x5lex+oSMGPOIMWapMWZpefk5HweiKOMef5w1pUzJviMUvju79l26EzDSxZEjR9i8eTMAjz/+ODfeeCMHDx4MrRk9/vjj6ZxeiGREqR6YFfZ+JnA8Vh8R8QDFQEuca2O1NwGTrI3IsWKNEYsrgEtF5BDwCrBARF6K+00VRUkKn32wRyszNOAppddVGpzoMLHDd+effz6PPfYYS5YsoaWlhc9//vM88sgjvP/97+fqq69mzpw56Z4ikFz4bitQLSJVwDGcxIWPR/RZD9wFbAbuADYaY4yIrAd+ISLfwEl0qAbewPF6Btm012yyNtZZm8/EGyPWpI0x38NJkMBm6j1rjFmRxPdVFCUBwey7aCe4DhxdMapTGkQo0cG+n8jZdwAul4vvf//7Z7WtWrWKvXv3Duq7YsUKVqxYMUozO5uEomTXbz4LbADcwKPGmF0i8nVgmzFmPbAW+KmI1OJ4L2vstbtE5ElgN+AD7jPG+AGi2bRDfglYJyIPANutbWKNYW0dAooAr4jcDtwckR2oKMowEs9Tctn4S8bUvnOltyCrkhpJbZ41xjwHPBfR9tWw1z3AR2Jc+yDwYDI2bXsdTnZeZHu8MSoTzP8QUdLFFUUZGqGUcNfgFQCPbUv3mlKkp5SugqyZQGVlJTt3jo2tmlpmSFGUlBnwlAZ/FtQpX7o9pYFMByAsfJeGeaUz42+4GenvoqKkKErKBAKxPaVMOboiqElBMUpX+C4nJ4fm5uZxIUzB85RycnJGbAytfacoSsrE85Qy5eTZgfDd2Snhoz2tmTNnUl9fT2Nj4+gOPEIET54dKVSUFEVJGX88TylDEgoiU8KD+0RHWyyzsrJG7JTW8YiG7xRFSZmQKMWrfZcpnlJE+G48hNHGMypKiqKkjD9eSniGVE4Iik9k+C7dWYFKfFSUFEVJmXiiFArfpV2UnL8jq4SnO/9CiY+KkqIoKRP0NuJWdEj3mtKg2nfBdlWlTEZFSVGUlAnWtYt6dIVLEMmA8F2M2nfpnpcSHxUlRVFSJljXLlqiQ7A93Q//WIkOqkmZjYqSoigp47OeUrQ1JXC8pfSH785OdAiKU7pT1ZX4qCgpipIywVMpYomSxyXpT3Swfw9KdFBXKaNRUVIUJWUSeUpukbTvUwp5ShJZJTxtU1KSQEVJUZSUGagSHjt8l26PZODIdufvUEUHDd9lNCpKiqKkTDDRIVpKODhile6Hf2Ttu2BShqaEZzYqSoqipEwoJTxW9p0r/dl3MY9D1/hdRqOipChKyoQ8JXd0UcpyCf3+NHtKdo6RiQ5pnpaSABUlRVFSxpfAU/K4XfiCypUmzED+HTBw+KCG7zIbFSVFUVImEKfMEECWW+hPd/guItFhoPadilImo6KkKErK+Pzxs++y3C76fWn2lAbVvguWGUrXjJRkSEqURGSViOwTkVoR+XKUz7NF5An7+RYRqQz77H7bvk9EbklkU0SqrI391qY33hgiUioim0SkQ0S+HWYnT0R+KyJ7RWSXiPxr6rdHUZRoJEoJ97gzYJ9SZKKDfdqpp5TZJBQlEXED3wFuBWqAj4lITUS3e4BWY8x84GHgIXttDbAGWASsAr4rIu4ENh8CHjbGVAOt1nbMMYAe4CvAF6NM/z+MMQuBi4GrROTWRN9XUZTE+OIcXQHgcbnoT7NLEln7zmNVyaeZDhlNMp7SMqDWGFNnjOkD1gGrI/qsBh6zr58CbhDHZ14NrDPG9BpjDgK11l5Um/aaldYG1ubt8cYwxnQaY17BEacQxpguY8wm+7oPeAsYuYPlFWUCEUggSlluSfvDP7L2nTtUvVzjd5lMMqI0Azga9r7etkXtY4zxAW1AaZxrY7WXAqetjcixYo2REBGZBHwAeDHG5/eKyDYR2dbY2JiMSUWZ0PjiHIcOjlfiS/PDP7L2HTiJGekOKyrxSUaUov2vi/xXjdVnuNqTnccgRMQDPA58yxhTF62PMeYRY8xSY8zS8vLyRCYVZcITOnk2xj4ljzv9+5Qia99BZmzqVeKTjCjVA7PC3s8EjsfqY0WgGGiJc22s9iZgkrUROVasMRLxCLDfGPOfSfRVFCUJ/Ak8pSx3BnhKoTJDAzgenIpSJpOMKG0Fqm1WnBcncWF9RJ/1wF329R3ARuP8mrIeWGMz56qAauCNWDbtNZusDazNZxKMERMReQBHvD6XxPdUFCVJ/Imy71zpX1PyR1n3Uk8p8/Ek6mCM8YnIZ4ENgBt41BizS0S+DmwzxqwH1gI/FZFaHO9ljb12l4g8CewGfMB9xhg/QDSbdsgvAeusoGy3tok1hrV1CCgCvCJyO3Az0A78A7AXeMu68N82xvww9dukKEo4/mT2KWVI9l141QlnTUkTHTKZhKIEYIx5Dnguou2rYa97gI/EuPZB4MFkbNr2OpzsvMj2eGNUxph69J8YRVHOiZCnFLPMUPoTCoL7kcJ1Uz2lzEcrOiiKkjL+gEHEOTcpGh6XK+3hu2gbfDMhrKjER0VJUZSU8QdMTC8JbO27NIfvgh7RWdl3GeDBKfFRUVIUJWV8ARPz2ArIjPBdMA3qbE9Js+8yHRUlRVFSpt8fIMsd+/GRCWWGgp6SK2LzrFZ0yGxUlBRFSZlEouT1ZM6akiti82y656XER0VJUZSU8flNzLOUIDNSr6OJkset2XeZjoqSEpOTbT387PXD6Z6GkoH0+0388J3bRb/fpPWU10CUNSW3rillPEntU1ImJnf/eCu7T7RzU80UphTlpHs6SgbhCwTiJjpkuYIH6sVPiBhJYq8pqShlMuopKTFp7eoD0B9iZRAJw3fWi0qnVxIK30WUGUp3WFGJj4qSoigpkyjRIct6R+nMwIu6pqSeUsajoqQoSsokTgl3hCCdmW5Bh8gdmX1nRckYw7HT3emYmhIHFSVFUVIm8eZZ59HSn8ZQmT90ntJAW3iZoWffOcFV/7qRNw+3pmN6SgxUlJSEaLBDiaTfHyDLlTh8l05PyUSpfReefbdpXwMABxo6Rn9ySkxUlBRFSRmfP4GnZAUrnaIUXM4KX1PKcg9UdMj2uIH0enPKYFSUlITo+R9KJP0BEwrRRSMoWOl84Mc6uiLoKXnC0taVzEFFSUmI/sgqkfj8gdBepGh4g2tKacy+M1FSwsOz74JhvT6fekqZhIqSoigpkyh85/VYUfKlM3wXrfbdQE2+oKfU0+8f/ckpMVFRUhKi4TslkmQKsgL0+tL3wA+VGYqxTyn4eVefilImoaKkJETDd0ok/YH4ohRMIuhNY2gsuKYkYdMMP+Svz++IUbd6ShmFipKiKCmTqMxQtvWU0rleEzoOfZCn5MwpGFrU8F1mkZQoicgqEdknIrUi8uUon2eLyBP28y0iUhn22f22fZ+I3JLIpohUWRv7rU1vvDFEpFRENolIh4h8O2Jel4rIu/aab4nEOb9ZiYneNCWSfn/87LtMCN9FSwkPz77rsx16+jXRIZNIKEoi4ga+A9wK1AAfE5GaiG73AK3GmPnAw8BD9toaYA2wCFgFfFdE3AlsPgQ8bIypBlqt7ZhjAD3AV4AvRpn+94B7gWr7Z1Wi76sMRsN3SiS+QCC0QTYa2SFRSr+nFL7HN7yiQ1CUunVNKaNIxlNaBtQaY+qMMX3AOmB1RJ/VwGP29VPADdYrWQ2sM8b0GmMOArXWXlSb9pqV1gbW5u3xxjDGdBpjXsERpxAiMg0oMsZsNk5u6E/CbClJoB6SEgsnfJeMp5RGUYqSfedxu0JVwoOhRV1TyiySEaUZwNGw9/W2LWofY4wPaANK41wbq70UOG1tRI4Va4x4865PMG8AROReEdkmItsaGxvjmJxYqIekxMLJvovnKWVCooPzd/iaktcePhgImJAo6ZpSZpGMKEX7nxf5vIrVZ7jak51HMnMa3GjMI8aYpcaYpeXl5XFMTkzUY1IiSZQSnp1lPaU0PvCjFWQNenB9/kBoY6+KUmaRjCjVA7PC3s8EjsfqIyIeoBhoiXNtrPYmYJK1ETlWrDHizXtmgnkrSaAekxJOIGAIGOJvnnUPPPzThTEGl0B4flN2mCgNeEqa6JBJJCNKW4FqmxXnxUlcWB/RZz1wl319B7DRruOsB9bYzLkqnGSDN2LZtNdssjawNp9JMEZUjDEngDMicrldq/qzMFuKogyRYD27+PuUgp5SGo+uCJiz1pNgYM79vgFPSdeUMgtPog7GGJ+IfBbYALiBR40xu0Tk68A2Y8x6YC3wUxGpxfFe1thrd4nIk8BuwAfcZ4zxA0SzaYf8ErBORB4AtlvbxBrD2joEFAFeEbkduNkYsxv4DPBjIBf4nf2jpIiG75Rw+iPK9ERDRPC6XWlfU3JFzPHs8J3zPVSUMouEogRgjHkOeC6i7athr3uAj8S49kHgwWRs2vY6nOy8yPZ4Y1TGaN8GLI72maIoQyMY9gp6Q7HI9rjSvnk2UjdDYUVfIFRuSNeUMgut6KAkRNeUlHBCopTljtsvO8uV3tp3AXNW5h2EeUq+QCgMqaKUWagoKQmJs3SnTECCQuONs6YU/Dyd4Tu/ib2m1OcPhDbR9vsNvlFKyGjr6h+VccYyKkqKoqREb8hTShC+y3KnNXxnzNnp4HB2Tb5wIeoZhXn+7t0TXPj137OlrnnExxrLqCgpCVFHSQknKDTJeUrpC435olQyDw/f+cJOnB2NEN4f9jQA8OoBFaV4qCgpMVExUqIRFJrk1pTSmxLudsVICfcbfAFDjvX2RqP+3fHT3QAcbOoc8bHGMipKiqKkRG+SnlK6s++iHa8xkBLup98foCA7CxgdT6m9x1lPOtnWPeJjjWVUlJSYBOPx6jEp4SS7puT1ZICnFFF1Ijwl3Oc3FOU4u2JGo6pDW7cjSsdP9yToObFRUVJiomKkRCPZNaVsjzut6da+wOBK5uHVy/0BQ4EVpdHYQNtuRelUe49mtMZBRUlJiNGdSkoYQe8nJ4GnlOt1p7Vagi8QGLSm5A1bU+oPBCjIDnpKIzvPQMBwptdHvteNL2Bo7/YlvmiCoqKkKEpKDHhK8RMd8rLcaT1AL96aUk+/H2OgcJQ8pTO9PoyBqvJ8AJo7e0d0vLGMipKSEI00KOEMZN/Ff3zked109qbPI/AHzKBK5kFR6upz5jVaiQ7B0F1VWQEALZ19IzreWEZFSUmIapISTrK173K9njSH7wzuGGtKXdaDK8wZnfBdMMmhqjQPgGYVpZioKCmKkhKhlPAEopTvdTtrN2k6U8kfGBy+C56WGylKIx1mDHlKNnynnlJsVJSUhGimkBJOstl3uV5nzakrTetKsRIdROBMTzB8Zz2lEU5db4sI3zV36JpSLFSUFEVJiV6fH7dL8CQQpTyv88APrt+MNtESHUSE3Cw3HXatKz97lDwlu3G2rMBLQbZHw3dxUFFSEqJ+khJOny+QcD0JnEQHSKenZKIKZ57XzRkrEl63i2yPi54RrtEX9JSKc7Moyfdq+C4OKkpKQjR6p4TT6wskXE+CAVFKV1p4tDUlcMKKwTUej1vI9brpGfE1JR8ugXyvR0UpASpKiqKkRE+/P0lPKRi+S5+nFLmmBJCX5aHdril53C7ystx0jvAc27r7KcrNwuUSygq8NHWoKMVCRUlJAnWVlAG6+vwhwYlHMNGhM01rSv5AILGn5BKKcrNC4byRor2nn6IcZ09UaX62JjrEQUVJiYmWF1Ki0dPvJzfBsRWQ/vCdzx/DU/K6Q4kHHpdQlJMVWvMZKdq6+ynOdUSpvDCb5s4+AgH9+YpGUqIkIqtEZJ+I1IrIl6N8ni0iT9jPt4hIZdhn99v2fSJySyKbIlJlbey3Nr3nMMbnRWSXiOwUkcdFJCe126OArikpZ+N4SolFKT8DwnfRPKU8rztUFTw7y01RbhZtI1yLzgnfOfejrMCLP2Bo7dIQXjQSipKIuIHvALcCNcDHRKQmots9QKsxZj7wMPCQvbYGWAMsAlYB3xURdwKbDwEPG2OqgVZreyhjzAD+BlhqjFkMuG0/JUkE5wdaNUkJp6vPHwrNxWNgn1K6wnfRs+9yw0KP2R4XRbmeUDhvpGgP85TKCrMBdF0pBsl4SsuAWmNMnTGmD1gHrI7osxp4zL5+CrhBRMS2rzPG9BpjDgK11l5Um/aaldYG1ubtQxwDwAPkiogHyAOOJ/F9FYuG75RoJBu+y8+2a0q96ds8G9VTCpt7tsdFUU7WiItSW7cvtKZUVhAUJV1XikYyojQDOBr2vt62Re1jjPEBbUBpnGtjtZcCp62NyLFSGsMYcwz4D+AIcAJoM8b8PtoXFJF7RWSbiGxrbGyMeSMmKhq+U8JJNnyXm+XG7RI6ekf2gR+LaMehA2d5edkeN8W5WZzp9eEfwTWe9p4wT0lFKS7JiNLgf9XBEZ1YfYarPeUxRGQyjhdVBUwH8kXkzih9McY8YoxZaoxZWl5eHq2LoiiWZMN3IkJRjidtZwfFWlM6S5SyXBRZsRipDLyefj99vkBonHIrSo1nVJSikYwo1QOzwt7PZHAYLNTHhsqKgZY418ZqbwImWRuRY6U6xo3AQWNMozGmH3gauDKJ76tEoGE8JRwnfJc4JRygKDcrlOk22vT7AoOqhINTKDZItscV8mBGSjyDmX1BUSrK9eB1u3RNKQbJiNJWoNpmxXlxkgXWR/RZD9xlX98BbDROFc/1wBqbOVcFVANvxLJpr9lkbWBtPjPEMY4Al4tInl17ugHYk9xtUcLR8J0SxBhDV58vqfAdMCrrNbHo95uolSeK87yh19keN0W2Uvjp7pERiaAoTbKiJCKUFng1fBeDhL/uGGN8IvJZYANOBtujxphdIvJ1YJsxZj2wFvipiNTieC9r7LW7RORJYDfgA+4zxvgBotm0Q34JWCciDwDbrW2GMMYWEXkKeMu2bwceGeqNUhTFKTEUMCQVvgPHKxjpPUDRMMbQ549eDqkkXJSyXGHZcCMjEuF174KUFWSrKMUgKR/cGPMc8FxE21fDXvcAH4lx7YPAg8nYtO11DGTPhbcPZYyvAV+Ldo2SPOopKUGCG2GTyb4Dx1M61T76D98+f+yDCCfnD4hDvtdDReHIrvG0dUUTJS8NuqYUFa3ooMRExUiJJHiSbLLhu+Lc9ITv4p35VJI/4Cm5XRLKhmsYIfE8HQzf5Q2IUkVhTlrEeiygoqQkRBMdlCDB6gzJh+/Sk+jQF+d03PDwHUBOlpMWPlKeS7Tw3fRJuTR19I74MexjERUlJSHqMSlBgtUZkinIClCU46GnP0DvCJ9XFEkwfBdNlIKeUfAodHDq0Y1Y+M6KUmHOgCjNmJwLwIm2nhEZcyyT3P8sRVEUBo4RD3+gx2NgD5CP7ILkvKvhIF74zuUSfvGXy88K41UUZtNwZmQEoq2rj6Icz1kbeWdMckTp+OluqsryR2TcsYp6SoqiJE1wg2nSomS9g9HOwIsXvgO4cl4ZC6cWhd5PLcrh5Ah5LW3d/RSHrScBzLSe0rHW7hEZcyyjoqQoStIED8cryslK0NNhsvVGRvuk1d4EohTJ7NI8TrT3jMgaT2tXP5Mj1rGmFucgAvWnVZQiUVFSEqJrSkqQjhTDd2UFzsN4tA+164+zphSNOaV5GAP1rV3DPpfGM72h0kJBstwuphTmqKcUBRUlRVGSJrimVJCdnCiF6ryNckmdYPguO8qaUjTmlDrrOoebh1+UGs70UlGUPah95uTcERHBsY6KkpIQTQlXgpzp6SfP6456TlE0guG70faU4mXfRaPSitKhYRYlf8DQ0jnYUwKYW57PgcbOYR1vPKCipCREw3dKkDM9vqS9JHDCVJPzska9pE6iRIdIJudlUZTj4UBjx7DOo7mzl4BxUs4jmVdeQFNHb6jig+KgoqQoStKc6e1Pej0pSGlBNk1n0hO+S1aURISa6UXsOt6e8ljGGL74329z5w+30NF7dqXxYJWI8sKcQdfNrygAoHaYhXCso6KkJEQdJSXImR7fWZtAk6GswEtz5+h6Sj12s26OJ/m9UYunF7P3RDs+G/pLljcPt/LUm/W8UtvE2j8ePOuzoy1OOHBWSe6g6+aVO6J0oEFFKRwVJSUmKkZKJO09vpQ9Jaci9uh6SsEj2JOt0QewaEYRvb5Ayus82w63AnDpnMn89PVDZ1WvCK5RBRMpwplVkofX41JPKQIVJSUhRheVFEt7d/9ZNdySoaLQ2Zg6mv+PulOs0QdwwYxJAGw/0prSWLUNHZQXZvM3N1TT1NHH7949GfrscHMnZQXeqOtwbpcwr7yAPSdSDxmOZ1SUlJgEi6KoJClBmjt6Kc33Ju4YxozJuXT3+2kdxQX9YOHYZGv0Acwrz6e8MJvXDjSnNNb+hg6qKwq4Zn4ZVWX5/GTzodBne06eCYXporFkRjHvHmvTX/zCUFFSYqI/Jko4/f4A7T0+SvIHZ5LFI1jnbTQ3inb1+/B6XGfVm0uEiHDlvFJeO9CctEgYYzjQ0MH8igJcLuHOy+fw1pHT7DzWRq/Pz57j7Vw0e1LM65fMKuZ0Vz9HW3QTbRAVJSUh+kucAtDa5awLleSnFr4L1Xk7PXobRbv7/CmtJwW5an4ZTR297E4ypHaqvZeOXh/VNpPujktnkpvl5iebD7H5QDN9/gCXzSmJef0SGzJ859jplOc6XlFRUhQlKVo7nfBbqp5SUJTqR9NT6vOTl+TpuOHcsLACt0v47Tsnkuq/v+EMAPOsKBXnZnHHpTP55VvH+OozuyjOzeLq6rKY1583tRCv28U79W0pz3W8oqKkJIG6SgqhtO7JKXpKxblZ5HvdHBvF4qNdfb6UkhyClBZkc9X8Mn7zzvGkQni1Np27uqIw1PZ3q87jghnFnGjr5msfqCEnjjh6PS6WzCxmy8GWhGP9YfcpNu49lcS3GNuoKCkJ0fCdAgOeUmmKnpKIMHNyXmjPzmjQ1edPKckhnA9eOJ2jLd1srkuc8LC/oYPi3KxQ4VlwDvP71V9dyc5/voUPXTIzoY0r55Xybv3puCf0tnb28Rc/2cbdP94WOmhxvJKUKInIKhHZJyK1IvLlKJ9ni8gT9vMtIlIZ9tn9tn2fiNySyKaIVFkb+61N7zmMMUlEnhKRvSKyR0SuSO32KIoSpGWInhI41Qv2j+Im0a4+/5A8JYDblkyjJN/Lo68cSti31mbeiZydUCEiZCe5cfeKeWUEDLxRF9tbert+YM1p66HUUtbHGglFSUTcwHeAWx/S3TUAACAASURBVIEa4GMiUhPR7R6g1RgzH3gYeMheWwOsARYBq4Dviog7gc2HgIeNMdVAq7Wd8hj2mm8CzxtjFgIXAnuSvTHKAOooKQBNHX2IMOhsoGSonlLAkZauETmvKBrt3f1Jn/kUSU6Wm08sn82Le09Ra9eMYlFrM+/OhYtnTyLb4+LVA00x+4R7me/Wj++kiGQ8pWVArTGmzhjTB6wDVkf0WQ08Zl8/Bdwgzq8Oq4F1xpheY8xBoNbai2rTXrPS2sDavH0oY4hIEXAtsBbAGNNnjBnf/5rDjIbtlHBOtfdQVpBNVpIVwsOprijEmIE1mJGmvbufSXlDEyWAT11ZSb7Xw0PP74vZp6mjl5bOPhZMKYzZJxlystwsn1vKS/saY65jHW7uItvjorI0b9wnRSTzv2sGcDTsfb1ti9rHGOMD2oDSONfGai8FTlsbkWOlOsZcoBH4kYhsF5EfisjgWh+AiNwrIttEZFtjY2PsOzFBUXFSAE609TCteHBh0WRYMMXxJvYn8DyGi9NDqDwRTmlBNp9ZMY8Xdp9ic4zNtO+ddL7LeVPPTZQAbqqZwsGmzpiifaSli9kleSyaXsyek+O7AkQyohRt91nkYypWn+FqH8oYHuAS4HvGmIuBTmDQehiAMeYRY8xSY8zS8vLyaF0mJMEwue42VwBOtvUwpWhoolRZlo/X7WLPiZEXpX5/gK4+/zmJEsDdV1UxuySPLz/9TtTkgn2nnO9yrp4SwM01UwDYsOtk1M+PtHQxpzSP86cVcrSlO25SxFgnGVGqB2aFvZ8JHI/VR0Q8QDHQEufaWO1NwCRrI3KsoYxRb4zZYtufwhEpJUlUi5RwTrYP3VPKcrtYPKOItw6P/CJ9W7fzwD6X8B04dfP+/Y4lHG7u4oHfDl6O3nH0NBWF2Wdl3g2VKUU5XDRrEht2DU75NsZwpKWLWSV51EwvAmDvKIh7ukhGlLYC1TYrzouTVLA+os964C77+g5go3F+vV4PrLGZc1VANfBGLJv2mk3WBtbmM0MZwxhzEjgqIufZa24AdifxfZUIVJuUrj4fbd39TB2iKAFcMnsy7x5rC511NFIERelcPSWA5XNL+fS1c/nFliM8sfVIqN0Yw5a6FpZVlQzKvBsqty6eyrvH2qiLqBre3NlHV5+fOSV5nD/NEaXxXMQ1oSjZ9ZvPAhtwsteeNMbsEpGvi8gHbbe1QKmI1AJfwIbJjDG7gCdxxOB54D5jjD+WTWvrS8AXrK1SazvlMew1fw38XETeAS4C/r9Ub5CiKE7oDmDqEMN3AJfMmUyvLzDiD9TWTqcc0qQhZAlG4//cch7XVJfxj7/eyYt7HE9mx9HTnGzv4drq4Qv3337xDFwCT7917Kz2I6EzmfKYWpTDpLyscS1KSe0uM8Y8BzwX0fbVsNc9wEdiXPsg8GAyNm17HU52XmT7UMbYASyNdo2SPBrGU4IPxpmT84ZsY2nlZABePdDEhbNiFyk9V07Z016nFKW2yTcWHreLb3/sEj756BY+/dM3ue/6+Ww+0ExBtodVF0wdljHACeFdU13O02/V84WbFuCyxWSPhM5kynNOyJ1WlHRtvrGIVnRQEmI0gDfhOdTkHHxXWTZ0UaoozOGCGcVs3NMwXNOKysn2c/fqIinOy+Lnf7Gcm2qm8M0X97PtcAv/9MFFQ94LFYsPXzqT4209Zx2fcbi5C5GBXwjOn1bEvpNnUj4hd6wwtDociqJMKA41d5HvdVNecG7ex/ULK/j2xv20dPZRkuK5TMnS0N6D1+MaljWlcApzsvjenZdyuLkTr8fFtOLBR5yfKzfXTGFSXhY/2XwoVMj1SEsXU4tyQjX0zp/mnJB7qLmT+RXnnvmXaainpCRGHaUJz8GmTirL8s95Uf/mmikEDPz2ncgE3uHjZHsPU4tyhi0BIZI5pfkjIkjgbKS9c/kcXthzKuSd1jZ2UFU2sMWyxiY77Do+PkN4KkqKoiTkULMjSufK4hnFLJpexLqtRxN3HiKHm7uYVTIyojEa/NkVc8hyuVj7ykH6/U5iyOIZxaHP51cUkOWWUdnzlQ5UlJSEqKM0senu83O0pSvusd6psOayWew63s7WQ4mPa0iV4EmwwzXXdFBRlMOHL53J428cYd3Wo/T5Alwclhji9biYV14wbjPwVJSUhGj23cRm78l2AgYW2Y2b58odl86irCCbb/z+vWGxF07jmV7O9PrGtCgBfPHmBRTkePjKr3dSmO3huvPOTj2vmV6koqQoysQkmH4cXMs4V3K9bu67fh6b65p57t3kTnhNlnePOcVKFw5DPbp0UlqQzU/uXsb7L5jGtz528aCzoWqmFdFwppemjt40zXDkUFFSEqIp4ROb3cfbKcrxhI41Hw4+efkcLphRzD/+eicn2obvRNpth1vJcsuI7oMaLZbMnMR3PnEJ1y+sGPTZeK7soKKkxEHFSHEOmFs0vXhYs9k8bhff+NML6fMF+PMfbeV0V9+w2H35vUaWzJwU9wjy8cDi6cWIwPYj4+80HhUlJSG6pjRxae/pZ/fxdpZVlQy77eophXz3E5dQ19jJh7732jmftVTbcIZdx9u5dfHwVVnIVIrzslg4tYgtBxMf2T7WUFFS4uD8ZqyaNHF581ArAQPLR0CUAK5dUM5P71lGS2cf7/vWH/nGC+8N2Wv6r4215GS5WH1R5HFv45PlVSW8ebh1xAvcjjYqSkocVI4mOq/XNZPlFi6ePXnExlg+t5Tff/5abqqZwrde3M+V/7qRzz+xg+d3ngwVV42HMYYfv3qQZ3Yc5y+vmUt54fDUvMt0Lp9bQk9/gHePja8QnpYZUhKih/xNXF7Yc4rlVaXkekd2jaaiMIfvfPwS/nplOz965RDP7zrJr7Y71bIrS/OYX1HI7JI8pk/KoSDbQ67XTU+/nxNtPWza28Db9W3csLCCv7mhekTnmUksqyoF4PW6Fi6dMzKebDpQUVIUJSq1DR3UNXbyqSsrR23MhVOLeOiOJTzwJ4t583Arbx1p5e2jpznc3MVrB5ro6vMPuqZmWhEP3L6Yjy2bjds1MqWFMpGSfC8LphTwel0z910/P93TGTZUlJSYBKyDpH7SxOR3dg/RTfao7tEky+3i8rmlXD63NNRmjKG9x0dXn4/OXj85WS5K8r2D9vBMJK6eX87Ptxymp98/bjIOdU1JiUkobKeqNOEIBAxPbDvKFXNLR6z4aKqICMW5WUwrzmV+RQEzJ+dNaEECuO68cnp9AV6vGz9ZeCpKSkxUiyYuf6xtor61m48tn53uqShxWF5VQk6Wi/95rzHdUxk2VJSUmAw4SipPE43vv3SAsoJsblk0+qE7JXlystxcPreU/9mnoqRMADTrbmKypa6ZzXXNfGbFPLI942OdYjxz3YJy6po6Q8emj3VUlJSYhDwl1aYJg88f4F9+u5uKwmw+oaG7McF1C5wK4v+zf3x4S0mJkoisEpF9IlIrIl+O8nm2iDxhP98iIpVhn91v2/eJyC2JbIpIlbWx39r0DnUM+5lbRLaLyLPJ3xYFBtaUVJQmDj9+7RA7j7XztQ8sGjfZXOOdqrJ8ZpXk8j/7GtI9lWEhoSiJiBv4DnArUAN8TERqIrrdA7QaY+YDDwMP2WtrgDXAImAV8F0rEvFsPgQ8bIypBlqt7ZTHCJvb3wJ7krsdSjgavptYvFN/mn97fh83LKzgfReM//px4wUR4frzKni1tple3+B9XGONZDylZUCtMabOGNMHrANWR/RZDTxmXz8F3CBOSeHVwDpjTK8x5iBQa+1FtWmvWWltYG3ePsQxEJGZwPuBHyZ3O5RwdJ/SxKGhvYfP/Owtyguz+fePXDisFcGVkWfFeeV09/t54+Dwn+Y72iQjSjOAo2Hv621b1D7GGB/QBpTGuTZWeylw2tqIHCvVMQD+E/g7IG7FQhG5V0S2ici2xsbxEZcdDjTrbmLQ0tnHnWu30NrVx/fuvISSfG+6p6SkyBVzy/B6XGzaO/afX8mIUrRfmSKfVrH6DFd7ymOIyG1AgzHmzSifn93ZmEeMMUuNMUvLy8sTdZ8wDCQ6qDiNV+pbu1jzyGYON3fxw7uWsmTm2D8cbyKS63VzxdxSXnpv7K8rJSNK9cCssPczgeOx+oiIBygGWuJcG6u9CZhkbUSOleoYVwEfFJFDOOHBlSLysyS+r2IxEX8r44s3D7fyJ999jRNtPfzoU5dx5byydE9JOQeuP6+cusZODjd3pnsq50QyorQVqLZZcV6cpIL1EX3WA3fZ13cAG43z6/V6YI3NnKsCqoE3Ytm012yyNrA2nxnKGMaY+40xM40xldb+RmPMnUneFwVUjcYp/oDhWy/u509/sJmcLBdPf+ZKrpyvgjTWWXGec2z6S2N8I23CwlHGGJ+IfBbYALiBR40xu0Tk68A2Y8x6YC3wUxGpxfFe1thrd4nIk8BuwAfcZ4zxA0SzaYf8ErBORB4AtlvbDGUM5dwI2LCdRu/GD+/Wt/GPz+zk7aOnWX3RdP7l9sUU5WSle1rKMFBZlk9VWT6b9jVw1yhWdh9ukqpmaIx5Dnguou2rYa97gI/EuPZB4MFkbNr2Omz2XER7ymOEff4S8FKsz5XoqBaNH1o6+3j4hff42ZbDlOZn8801F02YE1onEivOK+cXW46M6arhE7vErhKXgQQHlaexSlt3P2v/WMfaVw7S3e/nU1dW8vmbFqh3NE65/rwKfvTqITbXNXO9DeeNNVSUlJhoRYexy+muPn6y+TA//GMd7T0+3n/BND53YzXVUwrTPTVlBFlWVUJulpuX9jaoKCnjDxWjscfh5k7WvnKQ/95WT3e/nxsWVvCFmxewaHpxuqemjAI5WW6unFfKpn2N/JMxY3ITtIqSkhDVpszGGMO2w62s/eNBNuw+icclrL5oBvdcXcX504rSPT1llFmxsIIX9zZQ19TJvPKCdE8nZVSUFGWM0tbVz9Pb6/nFliPsb+igODeLv1oxj7uuqKSiKCfd01PSxApbNfylfY0qSsr4RMN4mYMxhreOtPLzLUf47Tsn6PUFuHDWJP7tw0u47cJpE/54cAVmleRRXVHAS/sauOfqqnRPJ2X0f7CSEK2Bl34az/Sy/u3jPLn1KPtOnaEg28Mdl87k48tn63qRMojrF1bw41cP0dnrIz97bD3mx9ZsFWUC0dPv58U9DfzyrXr+571G/AHDkpnF/N8PXcAHL5w+5h42yuixYkE5j7xcx2sHmrmpZmwdaa//q5WEaPhu9AiG55568xjPvnOcMz0+phbl8JfXzOVDl8xggaZ0K0mwtLKEfK+bl/Y1qCgpipI6R5q7+NX2Yzy9vZ7DzV3kZrlZtXgqH7pkBlfOK8PtGnupvUr68HpcXF1dxkv7GjFjLDVcRUlJiDpKI8PJth6efec4v3nnBG8fPY0IXDG3lL9eWc2qxVMp0PCccg5cf14FG3adYn9Dx5jysPV/vZIQPU9p+Gju6OW5nSf5zdvH2XqoBWNg8Ywi7r91IbddOJ0Zk3LTPUVlnHDdeU5q+Ka9DSpKiqIM0Nbdz4ZdjhC9dqAZf8Awv6KAz9+4gNuWTGPuGNxLomQ+04pzWTi1kE37Gvj0dfPSPZ2kUVFSlBGgo9fHi3tO8Zu3T/Dye430+QPMLsnjf103lw9cOJ3zphSOqTi/Mja5bkE5j756kO4+P7nesVE1XEVJUYaJtq5+Xthziud3nuDl/U30+QJMLcrhz66YwwcunM6SmcUqRMqocuX8Mn7wch3bDrdwTXV5uqeTFCpKSlTC15F0SSk2TR29/H7XKX638wSbDzTjCximF+fwieWzuXXxNJbOmYxLM+eUNHFZ5WQ8LuG1A80qSsrYxh8IEyXNvzuLk209bNh1kt/tPMEbB1sIGJhTmsc911Rx6+JpXKgekZIh5Hk9XDx7Eq8daE73VJJGRUmJii+gQhTO0ZYunt/pCNFbR04DUF1RwGevn8+qxdM4f5quESmZyRXzyvj2xv209/SPicMdVZSUqPT7A6HXEzF85w8Y3q4/zaa9Dby4p4HdJ9oBWDS9iC/evIBVi6cxv0Kz5pTM58p5pXzrxf1sqWsZE9UdVJTGOZ9bt51rqsv58KUzU7qu3z/xlOhMTz9/3N/Ei3saeGlfA82dfbgEls4p4f5bF3Lr4mnMLs1L9zQVJSUunj2JbI+L1w40jR9REpFVwDcBN/BDY8y/RnyeDfwEuBRoBj5qjDlkP7sfuAfwA39jjNkQz6aIVAHrgBLgLeCTxpi+VMcQkVm2/1QgADxijPlmqjdorPPrHcf59Y7jKYtSd78/9Ho8e0p1jR1s3NvAxr0NvHGwBV/AUJybxYrzylm5sILrFpQzKc+b7mkqypDJ9ri5rLKEzWNkXSmhKImIG/gOcBNQD2wVkfXGmN1h3e4BWo0x80VkDfAQ8FERqQHWAIuA6cAfRGSBvSaWzYeAh40x60Tk+9b294Ywhg/438aYt0SkEHhTRF6ImPe4xhcWgkuV7j5/4k5jkD5fgG2HWnjRCtHBpk4AFkwp4C+umcvKhRVcMnsSHrcrzTNVlOHjinml/PuGfTR19FJWkJ3u6cQlGU9pGVBrjKkDEJF1wGog/OG+Gvgn+/op4NvirPquBtYZY3qBgyJSa+0RzaaI7AFWAh+3fR6zdr+X6hjGmM3ACQBjzBlre0bEvMc1necgLD3hntJwTCaNNHX08tK+RjbuPcXL7zXR0evD63ZxxbxSPnVlJSsXVjCrRMNyyvjlynmlALxe18xtS6aneTbxSUaUZgBHw97XA8tj9THG+ESkDSi17a9HXDvDvo5msxQ4bYzxRek/lDEAEJFK4GJgS7QvKCL3AvcCzJ49O1qXMUlnry9xpxh09YWH78aWLBlj2H2inY17Gti4r4EdR09jDFQUZnPbkmmsXFjBVfPL9DwiZcJwwYxiCrI9vHZgfIhStDzXyKdUrD6x2qPFRuL1H8oYzkUiBcAvgc8ZY9qj9MUY8wjwCMDSpUvH1hM4Dl19Qxel8DWlsUB3n59Xa5vYuK+BjXsaONneA8CFM4v53A0LuOH8CmqmFelGVmVC4nG7uHTOZLYebEn3VBKSjCjVA7PC3s8EjsfoUy8iHqAYaElwbbT2JmCSiHistxTeP+UxRCQLR5B+box5OonvOq7o6B26sHSFeVmZqtLHTnc7SQp7TvHagWZ6fQHyvW6uqS5n5fkVrDivnIrCnHRPU1EygmVVJfz7hn20dPZRkp+5yTvJiNJWoNpmxR3DSSr4eESf9cBdwGbgDmCjMcaIyHrgFyLyDZwkhGrgDRzvZpBNe80ma2OdtfnMUMaw601rgT3GmG+kemPGA13nEL5r6eobxpkMD/6AYcfRVl7c4yQp7D15BoDZJXl8fPlsVi6sYFlVCdmesVF4UlFGk2VVJQBsPdTCLYumpnk2sUkoSnb95rPABpz07UeNMbtE5OvANmPMepyH/09tkkELjshg+z2Jk1zgA+4zxvgBotm0Q34JWCciDwDbrW1SHUNErgY+CbwrIjusjb83xjw3tFs19uiwouT1pJ5J1toZJkppdJXauvt5+b1GNu519g61dvXjdgmXVU7mH953PtcvrGBeeb5WU1CUBCyZWYzX42LrwTEuSgD2Qf5cRNtXw173AB+Jce2DwIPJ2LTtdQxk6IW3pzSGMeYVoq83TRiCyQrZQxClls7+0OvRrH1njOFAYycb957ixT0NbDvcij9gmJyXxfXnVXD9wgquXVBOcW7ml0tRlEwi2+PmolmTeONQZq8rafrROKa9xxGWnKzUw1kn2rrJyXLR0z/0vU7J0uvz88bBltAm1sPNXQAsnFrIp6+dyw3nV3DRrMm4NUlBUc6J5VUlfPelA3T0+ijI0OzTzJyVMiw0nekFoHAI//kONnUyt6yA3SfaR6SiQ+OZXjbZTLk/7m+ks89PtsfFlfNKQ5tY9WhwRRleLqsswR+o5a3DrVy7IDOPslBRGsc0djiiFEhRVfp8AQ42dXJTzZRQIdJzxRjDruPtNknhFG/XtwEwtSiH1RfP4IaFFVw5r2zMnI6pKGORS+ZMxiVOsoOKkjLq1Ld2A6kXV32n/jS9vgCXVZbw7Dsnhryi1NPvZ3NdM3/Y7awPnWzvQQQumjWJL968gOsXOnuHNElBUUaHgmwPi2cU80YG71dSURrH7LMp075AautCz75zAq/bxeVzndIkqThaLZ19bNzbwB92n+Ll/Y109fnJ87q5prqML5y/gJULKzK+9paijGcuqyzhp68fptfnz8jtEypK45T9p87QYNeUUvGUTrR18+S2o9x6wVQm5SWX4dbW3c/vd53kN++c4NXaJvwBw5SibP7k4hncWDOFK+aWDinZQlGU4WdZVQlrXznIu/VtLK0sSfd0BqGiNA7p6ffz0PN78Xpc3FQzhZffa0zqus5eH3/187cIGMMXbz4vlE8fbU0qEDC8dqCZn285zIt7GujzB5hVksu9187l1sVTuWCGHgmuKJnIZVaIthxsUVFSRpauPh+/2HKEH7xcR+OZXr56Ww0n2rrxJeEp7T7ezuee2E5tQwff/cSlzCrJ47St6tDnGwj/+QOG9W8f47821lLX2MnkvCw+ecUcPnjhdJbMVCFSlEynJN9LdUUBWzN0v5KK0jigrbufx147xI9ePUhrVz9Xzivlvz52MZfPLeXfnt8bd03pQGMHD7/wHs++c4KSfC8/uXs5V1eXAYTizb1WlPafOsPnn9zBzmPtnD+tiIc/eiG3Lp6moTlFGWNcVlXCb3Ycxx8wGbf/T0VpDNN4ppe1rxzkZ68fpqPXxw0LK7hv5XwumT051MfjdtHvNxhjzvJijrZ08a0X9/PLt+rJyXJz3/XzuPeaeRSHrSMFyxP1+QJsqWvmz3+8lZwsN99ccxEfWDJdK24ryhhleVUJv9hyhN3H27lgZnG6p3MWKkpjkENNnax95SBPbDuKzx/gfRdM469WzKdmetGgvllWOHwBQ5ZbaDzTy39t3M/jbxxBRPjzq6r4zIp5UTPi3C7B4xIONXey9pU6pk/K5ed/sZwpRVp5W1HGMsHM2tfrmlWUlKHR6/OzYdcp1r1xhNcONON1u/jwpTP49LXzqCzLj3ldlvV2+v0Bfv76Yf5twz56fQE+etks/mZlNVOL4wtMtsfFr7YfI8/rZu1dS1WQFGUcMKUoh6qyfLYcbOYvr52b7umchYpSBtPr8/NabTPP7zzJht0nOd3Vz8zJuXzx5gX86dJZVCQhEB7rKX3l17v45Vv1rDivnK/eVsPc8oKk5hA8Uv0Ty2czpzS2+CmKMra4fK6zOT7T1pVUlDKMzl4fL+1r5PldJ9m0t4GOXh+F2R5Wnl/BHZfO5Kp5ZSmt5WS5HU/pl2/Vc/dVVXzltvOHlCH351dVpXyNoiiZy+VzS3n8jaPsOdHO4hmZE8JTUcoATnf18Yc9DTy/8yQv72+kzxegNN/LbUumccviqVw5r3TIO6+Dx1Z43S7uf9/ClAXp0U8tpbmjj+laHFVRxhXLqwbWlVSUFBrae9iw+xQbdp5kc10z/oBhenEOn1g+m1WLprK0smRYXOpL50wmyy383w9dEPKaUmHlwinnPAdFUTKPqcU5VJbm8XpdC39xTeasK6kojSLHTnfz/M6T/O7dE7x5pBVjYG55Pp++di6rRqgKQvWUQnZ/fdWQBElRlPHN5XNLee7dzFpXUlEaYbr7/Pxu5wme2HqULbYy78KphXz+xgXcungq1VMKR3wOKkiKokRj+dwS1m3NrHUlFaURorWzjx+9epAfv3aI9h4flaV5fPHmBdy2ZHrcFG5FUZTRIrhf6dXaJhWl8Yo/YPjZ64f59w376Oj1sWrRVD51VSXLq0q0LpyiKBnFtOJcFk0v4ve7T/Hp6+alezoAJBXXEZFVIrJPRGpF5MtRPs8WkSfs51tEpDLss/tt+z4RuSWRTRGpsjb2W5ve4R5jpDjd1cddj77B19bv4uLZk/j956/l+5+8lMvnlqogKYqSkdxcM5W3jrTScKYn3VMBkhAlEXED3wFuBWqAj4lITUS3e4BWY8x84GHgIXttDbAGWASsAr4rIu4ENh8CHjbGVAOt1vZwjzHstHb28ZHvb+aNgy089OEL+Mndy1gwCutFiqIo58LNi6ZgDPzm7RPpngqQnKe0DKg1xtQZY/qAdcDqiD6rgcfs66eAG8RxDVYD64wxvcaYg0CttRfVpr1mpbWBtXn7cI6R3G1JjT5fgE/9eCuHW7r48d2X8dHLZqtnpCjKmGDh1EKWVZbw7Y37OX66O93TSWpNaQZwNOx9PbA8Vh9jjE9E2oBS2/56xLUz7OtoNkuB08YYX5T+wzXGIETkXuBe+7ZDRJqBpmh9E3HVg0O5KmMpY4j3YRyi92IAvRcO4+4+zPjakC8tA+YMxxySEaVov/JHnhoXq0+s9mgeWrz+wznG4EZjHgEeCb4XkW3GmKXR+k4k9D4MoPdiAL0XDnofBrD3onI4bCUTvqsHZoW9nwkcj9VHRDxAMdAS59pY7U3AJGsjcqzhGkNRFEXJUJIRpa1Atc2K8+IkFayP6LMeuMu+vgPYaIwxtn2NzZyrAqqBN2LZtNdssjawNp8ZzjGSuy2KoihKOkgYvrPrN58FNgBu4FFjzC4R+TqwzRizHlgL/FREanG8lzX22l0i8iSwG/AB9xlj/ADRbNohvwSsE5EHgO3WNsM8RiIeSdxlQqD3YQC9FwPovXDQ+zDAsN0LcZwNRVEURUk/WhRNURRFyRhUlBRFUZSMQUUpjNEuS5QORORREWkQkZ1hbSUi8oIt7fSCiEy27SIi37L34x0RuSTsmrts//0icle0sTIZEZklIptEZI+I7BKRv7XtE/Fe5IjIGyLytr0X/2zbh63k11jCVoTZLiLP2vcT9T4cEpF3RWSHiGyzbSP/82GM0T/OupobOADMBbzA20BNuuc1At/zJNTnoQAAAw1JREFUWuASYGdY278BX7avvww8ZF+/D/gdzl6wy4Ettr0EqLN/T7avJ6f7u6V4H6YBl9jXhcB7OOWoJuK9EKDAvs4Cttjv+CSwxrZ/H/iMff1XwPft6zXAE/Z1jf25yQaq7M+TO93fbwj34wvAL4Bn7fuJeh8OAWURbSP+86Ge0gCjVpYonRhjXsbJXgwnvIRTZGmnnxiH13H2kE0DbgFeMMa0GGNagRdw6g6OGYwxJ4wxb9nXZ4A9OJVAJuK9MMaYDvs2y/4xDF/JrzGDiMwE3g/80L4fztJn44ER//lQURogWjmlGTH6jjemGGNOgPOwBipse6x7Mq7ulQ27XIzjIUzIe2FDVjuABpwHxwGSLPkFhJf8Guv34j+BvwMC9n3Spc8YX/cBnF9Mfi8ib4pTig1G4edDz1MaIJlyShONVEs7jTlEpAD4JfA5Y0y7xC6kO67vhXH29l0kIpOAXwHnR+tm/x6X90JEbgMajDFvisiKYHOUruP6PoRxlTHmuIhUAC+IyN44fYftXqinNMBELkt0yrra2L8bbPu4LuEkIlk4gvRzY8zTtnlC3osgxpjTwEs46wLDVfJrrHAV8EEROYQTvl+J4zlNtPsAgDHmuP27AecXlWWMws+HitIAE7ksUXgJp8jSTn9mM2suB9qsy74BuFlEJtvsm5tt25jBxv7XAnuMMd8I+2gi3oty6yEhIrnAjThrbMNV8mtMYIy53xgz0ziFRdfgfK9PMMHuA4CI5ItIYfA1zv/rnYzGz0e6Mzwy6Q9OBsl7OPH0f0j3fEboOz4OnAD6cX6LuQcnDv4isN/+XWL7Cs5BiQeAd4GlYXbuxlnArQX+PN3fawj34WqcMMI7wA77530T9F4swSnp9Y598HzVts/FeZjWAv8NZNv2HPu+1n4+N8zWP9h7tA+4Nd3f7RzuyQoGsu8m3H2w3/lt+2dX8Hk4Gj8fWmZIURRFyRg0fKcoiqJkDCpKiqIoSsagoqQoiqJkDCpKiqIoSsagoqQoiqJkDCpKiqIoSsagoqQoiqJkDP8/XqW/tC349s4AAAAASUVORK5CYII=\n", + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAaUAAAD4CAYAAABMtfkzAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAgAElEQVR4nOydeXidVbX/P+vMmdOmTad0Tkon2kJLi8yUWZDitUhVFBVFvKDXiQvc63D1ig/wQ7gqIhdBL4JSsIIUZBIKMkkH2gJt6ZAOtOnczOPJGdbvj/dNcnJypqRJzkmyP89TOGe/+117nTR9v2ftvfbaoqoYDAaDwZAJONLtgMFgMBgMbRhRMhgMBkPGYETJYDAYDBmDESWDwWAwZAxGlAwGg8GQMbjS7UCmMWLECJ00aVK63TAYMp7AgU20OrPIGTW1U3tjXRU5DR/ROqwUT1ZemryzaDn4ISpOskZPIxhW5ND7BDzD8I2YkFa/BiPvvvvuMVUdebx2jChFMWnSJNatW5duNwyGjOfAj6dRkTeXhd/5c6f2dS//mQVvfoVdl9/HlJPPS5N3Ftv/ez4tniLm3PwS1Y2tcOdkDk24lBnXPpBWvwYjIvJRb9gx03cGg6FHOAiDdH2EiNP6rqvhUH+71AVBQazXDocQxAEZ4JchPkaUDAZDjxANozFEyeGwRSkU7G+XuqJKmyo5HULYiFLGY0TJYDD0CAdhYj5C7EgpHE6/KAmKtomSCEGcoEaUMhmzppQCgUCAiooKWlpa0u2KIQk+n4+SkhLcbne6XRn0OFBUnF3bHVabhtL/8BcAsUTJ4YCwOhAjShmNEaUUqKioIC8vj0mTJiH2L7gh81BVKisrqaioYPLkyel2Z9DjIAyOrv8eHG2RUiZM3xExfSdmTWkgYKbvUqClpYWioiIjSBmOiFBUVGQi2n5CCKN0jZQyLdFBo9aUJAOmFQ3xMaKUIkaQBgbm76n/cBK25sSicDitNs2Uh7/9OyH2mpJoOM0OGRJhRMlgMPSIeCnhDqcHyJQ1pY5ICbAiJc0QsTTExIjSIOK1117jsssuA8Dv93P++eczb948Hn/88S59v/Wtb/H6668DViLHLbfcQllZGbNnz2bhwoU8//zzAPzsZz9rv6empob77ruvV3z1+/1cddVVlJaWsmjRIvbs2ROz3wsvvMAJJ5xAaWkpt99+e3v7smXL2LFjR6/4YugZDg0nTnTIgEjJioo6RCkkJvsu0zGiNEjZsGEDgUCAjRs3ctVVV3W6VlVVxTvvvMNZZ50FwA9+8AMOHjzIpk2b2LRpE8888wz19fVA34nSQw89xLBhwygvL+fb3/42N998c5c+oVCIG264geeff54tW7bw2GOPsWXLFgC+/vWvc+edd/aKL4ae4SQMMURJMijRITL7DqxIyWFEKaNJSZRE5GIR2SYi5SJyS4zrXhF53L6+WkQmRVy71W7fJiIXJbMpIpNtGztsm55EY4hIkYi8KiINInJvHP9Xisim1H4kmceePXuYPn0611xzDXPmzGHp0qU0NTUBViQxffp0zjjjDJ588kkAjhw5wtVXX83GjRuZN28eO3fu7GRvxYoVXHzxxQA0NTXx29/+ll/96ld4vV4ARo0axac//WluueUWmpubmTdvHp/73Oe45ZZb2LlzJ/PmzeOmm246rs/09NNPc8011wCwdOlSXnnlFaJPQV6zZg2lpaVMmTIFj8fDsmXLePrppwE488wzefnllwkG0//gG6o4iLN51mkLVQZESpHZdwBhnBA2a0qZTNKUcBFxAr8GLgAqgLUislJVt0R0uxaoVtVSEVkG3AFcJSIzgWXALGAs8LKITLPviWfzDuAeVV0uIvfbtn8TbwygBfgBMNv+E+3/vwAN3fqpJODHz2xmy4G63jIHwMyx+fzoE7MS9tm2bRsPPfQQp59+Ol/+8pe57777uPHGG/nqV7/KqlWrKC0tbY+IiouLefDBB7nrrrt49tlnu9h66623WLp0KQDl5eVMmDCB/Pz8Lv1uv/127r33XjZu3AhY4rhp06b299GceeaZ7RFWJHfddRfnn39+p7b9+/czfvx4AFwuFwUFBVRWVjJixIiYfQBKSkpYvXo1AA6Hg9LSUt577z3mz58f/wdn6BtUcUkYHF0fIc5My76LjJTEgcOsKWU0qURKC4FyVd2lqq3AcmBJVJ8lwMP26xXAeWKlQS0BlquqX1V3A+W2vZg27XsW2zawbV6RaAxVbVTVN7HEqRMikgt8B/hpCp8zoxk/fjynn346AFdffTVvvvkmW7duZfLkyZSVlSEiXH311SnZOnjwICNHHncx3y688cYbbNy4scufaEECukRF0DVzLlmf4uJiDhw40AueG7qNncEWK1LKtJTwTmtKONt9N2QmqWyeHQfsi3hfASyK10dVgyJSCxTZ7e9E3TvOfh3LZhFQo9r+VSayf7wxjiXw/b+BnwNNiT6giFwHXAcwYULikvbJIpq+IvqBLRFprt0lKyurfS9PaWkpe/fupb6+nry84ztmoDuRUklJCfv27aOkpIRgMEhtbS3Dhw+P2aeNiooKxo4d2/6+paWFrKys4/LZ0EPaBMcRI9HBFqVMmL6LFiUrUkq/WBrik0qkFOupF/0VNl6f3mpP1Y8Oh0TmAaWq+lS8Pu1GVB9Q1QWquqAvIojeYO/evfzzn/8E4LHHHuOMM85g+vTp7N69u33N6LHHHkvJ1owZMygvLwcgOzuba6+9lm9+85u0trYCViT16KOPAuB2uwkEAgDk5eXFFJ02uhMpXX755Tz8sBX4rlixgsWLF3cR2FNOOYUdO3awe/duWltbWb58OZdffnn79e3btzNrVnq+JAx12jPrYiQ6ZNT0nWqnaC6M05QZynBSEaUKYHzE+xIges6kvY+IuIACoCrBvfHajwGFto3oseKNEY+PAfNFZA/wJjBNRF5L+EkzmBkzZvDwww8zZ84cqqqq+PrXv47P5+OBBx7g0ksv5YwzzmDixIkp2br00kt57bXX2t//9Kc/ZeTIkcycOZPZs2dzxRVXtE/vXXfddcyZM4fPfe5zFBUVcfrppzN79uzjTnS49tprqayspLS0lLvvvrs93fvAgQN8/OMfB6y1pnvvvZeLLrqIGTNm8OlPf7pdhA4fPkxWVhZjxow5Lj8MPSMUtL6oaIw1pUyOlFRM7buMR1UT/sGa4tsFTAY8wHvArKg+NwD326+XAU/Yr2fZ/b32/bsAZyKbwJ+BZfbr+4F/TTRGhA9fBO6N8xkmAZuSfVZVZf78+RrNli1burT1J7t379ZZs2b1qs3TTz9dq6ure9Vmf3L33Xfrgw8+GPNauv++hgL++irVH+XrG3/4ry7Xjhw9qvqjfF33p67X+psDP5qqa++5sv396z8+T/f97OQ0ejR4AdZpCs/YZH+SRkpqre/cCLwIfGiLwWYR+YmItM2lPAQUiUg5VmLBLfa9m4EngC3AC8ANqhqKZ9O2dTPwHdtWkW077hgAdjR0N/BFEamws/4MCfj5z3/O3r170+1GjyksLGxPKTf0P217kGKnhLdFSpkQkSiRE0IqThzYfu1/Fx6/GoKt6XHNEJOUqoSr6nPAc1FtP4x43QJcGefe24DbUrFpt+/Cys6Lbk80xqQk/u8hRrr4QGHSpEls2tS726wWLYrOVRlYfOlLX0q3C0OatrOSJNaakitzpu8caOfNsxJR++7Zb8PB9+DYNhh9Ypo8NERjKjoYDIZuE060puSyz7LKkEgpsvadRlZ0aBPUoD8NfhniYUTJYDB0m3DIjjZipIS72is6pF+UrDJDEdl34uwQJZdVwYSgOeokkzCiZDAYuk3b9J0j1j4lEQLqRDMgy806sr2DTqLUJlahQD97ZUiEESWDwdBtQm3FVmOIUsYdpieRKeFOpF2o7HYjShmFEaVBxGA8umLSpEmceOKJzJs3jwULFrS3f+9732PVqlW94ouh+7TtU5JYte9ECOHIiCMiupyn1ClSahMls6aUSRhRGqQMhqMr2nj11VfZuHEj69ata2/7xje+0el8JUP/0pYSLs5Y5ykJQRwZsqakndaUVBwdU3ptomQSHTIKI0oDgKF6dEUiJk6cSGVlJYcOHTouPww9I2yfKhsrJRysc4syRpToPH3nbI/g2iIls08pk0hpn5IhgudvgUMf9K7N0SfCJYm/9Q/FoyvAKjh74YUXIiJ87Wtf47rrrmu/dvLJJ/PWW2/xqU99Ku7PzdA3tEVK7RtlowhlSI05ibVPKTpSMqKUURhRGiBEH13xy1/+kvPPP7/96Iq29gceeCCprb48uiJVYkVFsSqev/XWW4wdO5YjR45wwQUXMH369PZpR3N0RfpoP1U2jiiFyYwac9FrSogTV/shBG3Td0aUMgkjSt0lSUTTVwzFoyuA9qMqiouL+eQnP8maNWvaRckcXZE+wvbUnCPTp++085pSSNw4aatwbhIdMhGzpjRAGIpHVzQ2NraP19jYyEsvvcTs2R3VorZv397pvaH/CCVIdAAIihPJgBNeJep0m7DDjZOwfSS6mb7LRIwoDRCG4tEVhw8f5owzzmDu3LksXLiQSy+9tD1BIxAIUF5e3ilN3NB/tJ2VJDH2KYFVzicTTngVOheNDbedihMOEGhzz0zfZRRm+m6A4HA4uP/++7u0X3zxxWzdurVL+znnnMM555wT09aZZ57JrbfeSk1NDYWFhXg8Hu68807uvPPOLn3vuOMO7rjjjvb3f/rTn3r+ISLw+Xz8+c9/7tI+duxYnnvOqtM7ZcoU3nvvvZj3P/vssyxduhSXy/wKp4OwveHU4XTHvB7CiWTC9B0RERFWpARAqJUdh6qZCTQ1N5OdFu8MsTCR0hBloB9dEQwG+e53v5tuN4YsaqeEx8u+y5xEBzpl39EmoqFA+7qq39/c734Z4mO+Zg4AzNEVXbnyypinmBj6ifZ9So7Y32uD4sqgNaWIfUqODlHySAgUgq0m0SGTMJFSinRnY6chfZi/p/5Bw0n2KYkLRwbUvnOgqMQSpVbcdhZe2FR0yCiMKKWAz+ejsrLSPPAyHFWlsrISn8+XblcGPalsnnWE01/oVFAk8nRcZ4couewTaNUkOmQUZvouBUpKSqioqODo0aPpdsWQBJ/PR0lJSbrdGPS0Zd8lipRcGTB9R1RKuDo91otwEFfbfiWTEp5RGFFKAbfbzeTJk9PthsGQMWj7mlKcRAeHC4dmQqTUOSWcNlEKtXaIppm+yyjM9J3BYOg27RUd4myeDYm744iINOKISgl3OLuuKZnzlDKLlERJRC4WkW0iUi4it8S47hWRx+3rq0VkUsS1W+32bSJyUTKbIjLZtrHDtulJNIaIFInIqyLSICL3RtjJFpG/ichWEdksIuacA4Ohl1B7Tcnpir1PKSwunBmxpkTclPC2NSVTZiizSCpKYtWm/zVwCTAT+IyIzIzqdi1QraqlwD3AHfa9M4FlwCzgYuA+EXEmsXkHcI+qlgHVtu24YwAtwA+A78Vw/y5VnQ6cBJwuIpck+7wGgyE5ak99xavoEBYXzgxYU3KI0ukx57KOZ9FQa8SaUvrF09BBKpHSQqBcVXepaiuwHFgS1WcJ8LD9egVwnliFzJYAy1XVr6q7gXLbXkyb9j2LbRvYNq9INIaqNqrqm1ji1I6qNqnqq/brVmA9YFbADYZeoG1NyRVv86zDhYM0i1JbtmxEpCR2pBQOdKwpiYmUMopURGkcsC/ifYXdFrOPWl+haoGiBPfGay8CalTbv2JFjhVvjKSISCHwCeCVONevE5F1IrLOZNgZDMnRJGtKYXFHHKaXHlSjzk0CxE50CAU7IiXJgGlGQwepiFKssxGiN+zE69Nb7an60QURcQGPAb9U1V2x+qjqA6q6QFUX9MU5QwbDoKNt82ycNSV1uHClOfsuHG57PHQ85tr8DQX8OO01pUzYT2XoIBVRqgDGR7wvAaJPVmvvY4tAAVCV4N547ceAQttG9FjxxkjGA8AOVf2fFPoaDIYUaIuUnHEiJXW42x/66aLNx85n/NmRUmuLdYQF4AibfUqZRCqitBYos7PiPFiJCyuj+qwErrFfLwVWqVX+YCWwzM6cmwyUAWvi2bTvedW2gW3z6SRjxEVEfoolXt9K4XMaDIZUaS8zlChSSu+aksaYZHG4rUSHsL+ho81EShlF0s2zqhoUkRuBFwEn8DtV3SwiPwHWqepK4CHgEREpx4peltn3bhaRJ4AtQBC4QdWaaI5l0x7yZmC5LSgbbNvEG8O2tQfIBzwicgVwIVAH/CewFVhvHyB3r6o+2P0fk8Fg6ISdseZ0eWJeDjvcHdltaULbpu8iNs+2+RtubexoM6KUUaRU0UFVnwOei2r7YcTrFiBm2WZVvQ24LRWbdvsurOy86PZEY0yK43r3zwo3GAzJsR/kDnfsSAmHq2MfUJrQtkSLyESHtjWwSFHKgMoThg5MRQeDwdB97M2zrjiREk63VTEhjUWM22b3Ncb0nfqbAGhUr4mUMgwjSgaDoduIBgir4Ixz8m/7ERHpPH3WFiWJiJTapu80YEVKTfhMpJRhGFEyGAzdJxQiiAOnxJkhjzi3KF2E2/cpRaaEW5GS2NN3jeqz1r7MsTQZgxElg8HQbUQDBHHhdMQRpbasvDROjWnYFqWI6Tun255ubLWy75qwz94yx1dkDEaUDAZDt5FwkCDOTlNjnbAjJU1jXbn24CfCR4/LSbN6cLTWA9CIFTkZUcocjCgZDIbuY4tSXOyaeIHW9D3sNcb0ncshNONB/JYoNakdKZnTZzMGI0oGg6HbOMLW9F1cXG015tJX7LRt+i4ymnM5HbTgwdlaC0CTiZQyDiNKBoOh+ySJlMSevgsGMiFS6hAlt1NoVi/O9um7LOuCEaWMwYiSwWDoNhIOEpIEouRsK3yaxuy7cFtKeOT0nQM/HlwBS5Qa1CQ6ZBpGlAwGQ7eRcJBQokjJnr5LZ6QUDnet6OB1O2jBjStsTSs2muy7jMOIksFg6DYSDhCS+GtKHaKUvjWltn1KkWtKXpeDZvW2v29Ue/oujWtfhs4YUTIYDN3Gmr6LL0oOO/suHExjtYT2/bAdjzmf20kLHaWRWpzZ1gtzJHrGYETJEJc9297jjfv/LWITosFg4dAgoQTZd46IE17TRcg+sl0cUZFShCgFnTl2ZxMpZQpGlAxxcT92JWce+j8O7495YK9hCCPhIOFEiQ5t5xZlxPRd50jJHylK7jZRMmtKmYIRJUNc0n0ejiFzEQ0STrimZCUQhNO5VhPuWpDV5ZBO03fqzrX+bzbPZgxGlAwGQ7dxaihhpOTwWAkE4dbm/nKpC+3Zd44OP0WEgMPX0cdjRUqhNEZ0hs4YUTLEReh6Ho3BAODQACFHnAP+AJfHevCHWlv6y6UudGye7SyeAenIvlNPHpDeyhOGzhhRMsSlTYriFt00DFkcGkITTN+5PW3Td+kTpY59Sp0fc83OvPbXTo+VfZdO8TR0xoiSISnmpBlDNE4NEnbEFyWXt236Lo0P+3Bb9l3nx1yTM7/9tdtn+WlEKXMwomQwGLqNI0mig9trRSDhQDrXlGJP3zW7CtpfO7xWokPIPh69T2k4Cjv+3vfjDHBSEiURuVhEtolIuYjcEuO6V0Qet6+vFpFJEddutdu3ichFyWyKyGTbxg7bpifRGCJSJCKvikiDiNwb5dd8EfnAvueXYuahuomdvZRmLwyZh1NDnRIIovHYkZKmtUq4lT0aHSn53R2Rksdni6e/oe8deuEW+ONSqNzZ92MNYJKKkog4gV8DlwAzgc+IyMyobtcC1apaCtwD3GHfOxNYBswCLgbuExFnEpt3APeoahlQbduOOwbQAvwA+F4M938DXAeU2X8uTvZ5DV0xiQ6GaJwEUYmf6OD1egippLV8j8aJlPzujkgpy+ulRd2ofTx6n7L5Sev/Bzf2/VgDmFQipYVAuaruUtVWYDmwJKrPEuBh+/UK4Dw7KlkCLFdVv6ruBsptezFt2vcstm1g27wi0Riq2qiqb2KJUzsiMgbIV9V/qqoCf4iwZTAYjgOnhtAEa0pelws/HjSNiQ7t5ylFRUq1vnEArAtPI8frpAlv/4hSGzX7+m+sAUgqojQOiPwpVthtMfuoahCoBYoS3BuvvQiosW1EjxVvjER+VyTxGwARuU5E1onIuqNHjyYwObQQk+JgiIOLIJogJdzrduDHneZIyU50iMq+c7izuNR/G19r/TZ5PjdN+KC1j9eUgq3QlqJef6hvxxrgpCJKseZuop9W8fr0VnuqfqTiU9dG1QdUdYGqLhg5cmQCkwaDAWxRcsYXJY/TEiXJgEgpeu0ry+Nks06mkgLyfW6a1YsE+jhSaq5ufxmsO9i3Yw1wUhGlCmB8xPsS4EC8PiLiAgqAqgT3xms/BhTaNqLHijdGIr9LkvhtMBh6gIcAYYcn7nWHQ2jFjaSx0GlbogNR03d5vo5px/wsF414IdDHkVJzx6OqoXJ/3441wElFlNYCZXZWnAcrcWFlVJ+VwDX266XAKnsdZyWwzM6cm4yVbLAmnk37nldtG9g2n04yRkxU9SBQLyKn2mtVX4iwZUgBk+BgiEk4jJsQ6vQm7NaKB0c6p+/aC7J2jpTyfR0RXp7PTbP6cPS1KDVVAlCnWWhTdZLOQ5v4K5U2qhoUkRuBFwEn8DtV3SwiPwHWqepK4CHgEREpx4peltn3bhaRJ4AtQBC4QVVDALFs2kPeDCwXkZ8CG2zbxBvDtrUHyAc8InIFcKGqbgG+DvwfkAU8b/8xGAzHgx39qDN+pAQQEA+OcDoLssbePBsZKWW5nVTixRHsW1HSpkoE2KOjmeSv6dOxBjpJRQlAVZ8Dnotq+2HE6xbgyjj33gbclopNu30XVnZedHuiMSbFaV8HzI51zWAw9AwNtiCQNFIKiBtfGo+EaM++i0p0yM/qiJQ8LgfNeHEE+1YoWusr8QK7dQzTg2b6LhGmooMhBUwWnqGDYKsd/aQQKTnTGCm1F2R1RE/fdXwX97gcNKkXZ7BvEx38dccAK1LyaCuksdJFpmNEyZCc+Et3hiFIsK1OnCtxpBR0eHGG0xkptVV0iL+mlO229ik5g30rEoHGavzq4qAOtxqaEuVoDW2MKBmSY0TJEEG7KCWJlEIOT3pFyf69jRal4Tkdfmd7nTTiwx1s6tPf82BTLfVk48yxRanZJDvEw4iSIQWMKBk6aLUP7hOPL2G/kMODK42iRFukFLWmNLXYKsI6qSgbj9NBPbk4CEFr39W/C7fUUq9Z5BSMAECbTaQUj5QSHQxDG1PH1hBJ0G9FSs4k03chhxe3pnOfkv1lKipSyvW6+OkVs5k3vhARocVln6/UXAPePPqEljrqyaZgeDEchabaY+T0zUgDHiNKhqS074w3GICAPX3ncCdZU3Jm4dV0njwbOyUc4OpTJ7a/9rvyrQ0rLTV03tPfezj8ddRrNkUjx8A2aK45akQpDmb6zpACZvrO0EFb9p0zyfRd0JmFL42i1LZPySGJH3PtR1k0911auDNQTz3ZjBo1GoCW+mN9NtZAx4iSwWDoFkF7TcnlTrKm5M7BTdAqRpoGOqqEJ54QCnrsoyxa+k6U3IEGWhw5DC8spEXdhBoq+2ysgY4RJUNSTPKdIZKQHSm5kkRK6rYO0KOvi53GdcCKlKJr30UTahOlPoyUPKEGWl25DM/xUE0e4SYjSvEwomRIjlElQwShgDUl5/ImFiXc9qpJXx8LEYeOSCn+CbkAmlVoveirSCkcxhtuIuDOY1iOhxrNRUxKeFyMKBkMhm4RDliRkjtJpCReK/W6X44aj4Vd0cGRJFISbx4hHH23d6i1HgdK2JNHjsdJDXm4/EaU4mFEyZACJlIydBC2S+Qkm75zeK3pO39zfZ/7FItUI6Ucr4tacvuuykJLneWPNw8RocmZj6e1tm/GGgQYUTIkxczeGSJpj5S8WQn7OexIyd+YHlEiQUp4JNkeF8cohIbDfeOH3xIlvNbaVYu7AF/AiFI8jCgZUsDsUzJ0oHY2nceTWJRcPkuUWpvSFSm1iVLiSKkgy83BUCHaV8eU25GSI8tKPW/1FJITrjPf9uJgRMmQHPOPxxBB2D7i3JMk0cGdZVVHCLSkK1JKbfquMNvNEe07UQrZWX2ubCtSCvuG4SQMLSZaioURJUNSjCYZIpFAM0F1JBUlV5soNacn0SFsrym5UhElCpHGI9AH1UtaGixRcmfbWX7ZbUVZTf27WBhRMqSAUSVDBxJsphkvXnfih73Xnr4LpSv7zi7I6nAmEyUPR3QYEg62H1vem/htUfLkWKLksEUp1GhEKRZGlAwJsAqxqgmVDBFIsJkWPLiciR8fvlxrDSXckt5IyZlMlLKs6TsAGnp/Cq/VFh9fviVGrlyrUnhTzZFeH2swYETJkACN+r/BAI5gMy0kLsYK4PNlEVRH+vYptdW+SyFSOtR2+F5tRe+70VBJk3rJybEix6x8W5Rqj/b6WIMBI0qG5JhIyRCBM9iMX5KLUrbXRSO+Pj2nKBFtJ8+6XIkPIyzMcvORjrLeVO3ufT+aqqgmt/3E26zCkQC01pmirLFISZRE5GIR2SYi5SJyS4zrXhF53L6+WkQmRVy71W7fJiIXJbMpIpNtGztsm57jGOPbIrJZRDaJyGMikqQuiiEWRpIMkbhCLbSk8E8p2+OiTnNw+NOUZdaWEu5KXJA1P8tNteThd+ZAde+LkjRXUa157aKUXziSsAoBU5Q1JklFSUScwK+BS4CZwGdEZGZUt2uBalUtBe4B7rDvnQksA2YBFwP3iYgzic07gHtUtQyotm33ZIxxwDeBBao6G3Da/QzdxARKhkgcoRYCqURKHid1ZONsresHr2IQDgDgcrkTdnM6hGHZXo55xvVJpOTyV1OtueRnWeI4LM9HLTmEG0ykFItUIqWFQLmq7lLVVmA5sCSqzxLgYfv1CuA8sY4rXQIsV1W/qu4Gym17MW3a9yy2bWDbvKKHY4B1iGGWiLiAbOBACp/XEI1RJUMErlAzAUfySMntdFBHLu60iVJb9l3i6TuA4jwvB2V0n0RKbn8NNeSS67VFKdvDES3E2WQSHWKRiiiNA/ZFvDR2AV4AACAASURBVK+w22L2UdUgUAsUJbg3XnsRUGPbiB6rW2Oo6n7gLmAvcBCoVdWXYn1AEblORNaJyLqjR83iY1eMKBk6cIdbCDpTmwlvdubiDqRLlKzpO1eSRAeA0QU+doWLofojCAV61Q1foJoGR357tmK2x8lRhuFt7qOyRgOcVERJYrRFP6Xi9emt9m6PISLDsKKoycBYIEdEro7RF1V9QFUXqOqCkSNHxuoyxDGiZOjAHfYTSlGUWlx5eEPpqegg4QABdeJMkroOMDrfx3utJdaU37Ht3RvoWDn8agGs+33Xa+EQ3lADLe6CDr9EqHWNINtvvgDHIhVRqqDzwfUldJ0Ga+9jT5UVAFUJ7o3XfgwotG1Ej9XdMc4HdqvqUVUNAE8Cp6XweQ3t2Hpvpu8MEXi1hZAzcd27Nlpd+WSnSZQIBwnhwJrlT8yofB/vNNuTMgff7944q38DlTvg7z/sGmU1HMGB0uLt/GW3wTOCvGBln1SQGOikIkprgTI7K86DlSywMqrPSuAa+/VSYJVaOy5XAsvszLnJQBmwJp5N+55XbRvYNp/u4Rh7gVNFJNteezoP+DC1H4vBQiP+azBYeNSPulMTpZAnH6/603MkejhEkMSZd22MLvCxW8cQdmXBoQ+6N87+9db//XWw+/XO1+qs79T+7NGdmoPZo6z6d00m2SGapKJkr9/cCLyI9VB/QlU3i8hPRORyu9tDQJGIlAPfAW6x790MPAFsAV4AblDVUDybtq2bge/Ytops2z0ZYzVWQsR64AP7sz7Qg5+RwURKhjZU8eFHXSmKkn1cQzqKjzrCAYIpbsUcU+AjjIOmwmlwqBuRkioc2wEnfR5cWbD9xc7X6y1RCueO7dyeN8a+fjD1sYYIKX2NUNXngOei2n4Y8boFuDLOvbcBt6Vi027fRUf2XGR7T8b4EfCjWPcYUsdIkqGdoB8HCilGSvjaRKkGcvt5vTYcIkTyJAeAySOso9sP5syibP/T1jScM3EqOQD1h6C1HsbMhYYjsONF0DvAnjLU2v0I4CjsLEqeYWPhI2itPoBnzNxufazBjqnoYEiOiZQMNmpXZxBPTkr9JcuqKaf28Q39iWiQkKQmSiXDsnE7hU3u2RBohAMbUxukcgcA4eFlUHYBVO+ByvL2y8GaCvzqwldQ3Om27KISAOqO7E1tnCGEESVDAtoWiI0oGSz8DdY0nHrzU+rvtCtit9b3f/UC0dQjJadDmFiUw1uBaVbDnjdSG8TO1Lvg0YPcu3+q1RYxhRc4vJ09OprhuZ2zFQtHTSCgTvxHd6U2zhDCiJIhAXaig9Ekg01LQzUA4s1Lqb8j34oQWmr6f+1EwoGURQmsKbz3azwwckbXhIV4HNuB35HFzpY87lrdTLBoujWF1+bDsW3s1LGMK+w83Tl6WC4VOgLtg826Ax0jSoYUMKpksGhttKbhJCu1SMmTb2WdBWr76KjxBIiGCElq2XcApcW57D7WSLD0fNjzJqQy5XhsO/scJRRkWVUjtuWfCh+9bR2B3tqEt2Ef5TqWsdGilO9jr47CU/dRtz7TUMCIkiEB9mJt2IiSwSLQbFVncGYVJOlpkZefT4P6CNb1f/UCCYcIdeMRd+K4AgIhZfeIxdYm2h0xC8B0Qo9tZ1twNJfNGcPkETn8tWG2Vd5o12uwfx0ODbE+XMaYgs7TdzleF4ddY8hr7v2jMgY6RpQMBkPKBJqsNSV3iqJUlOPlmBYQru9/UXJ0I9EBYE6J9ZneaZ0MuaNhy9OJb2htQmor+DAwmtLiXC6cNYpH9o+y1ts++DPseIkQTnb7ZuOLcUpvU854skIN0GROoI3EiJIhBcyuc4NFwJ6+8+UWptR/RK6HYxTgaOr/kjqiQUIpbp4FGFeYxfAcD+9X1MGJS2H7C5BITO3Mu506ltLiXC6aNZqWsJNtEz8HH66Et3/FWu+pFBcXx7xdh022XvRBZfKBjBElQwJMooOhMyF7+i47b1hK/YfneDiqBbib+79ygSMcItyNSElEOGl8IWv3VMH8L1nTcBsfjX/D0W0AlOs4SotzmVdSSHGel/uCl8OcZejE0/iR/7NMGxU7KcQzejoA/oObY14fqhhRMqSAUSWDRailjoA6ycvLTam/y+mg3jUcX2v/T1E5NEi4G9l3AGeUjWBPZRP7HGNh0plWkdV4JZKObiOMk6PucYzO9+FwCBfMHMXfd9TR8on7qFjyF7a1DGP6mNhJIcPGT6dF3dTvfa+7H21QY0TJkABTkNUQRUsdDWSRl5X8jKI2mj1F5IRqIejvQ8e6Yq0ppT59B3BmmVV14o0dx+CMb0HtPnjvT7E7H9vGIdcYJhQXthd9vWjWaJoDIV7ffpS3d1rR4amTh8e8ffLIfLbpePTQpm75ONgxomRIgBEjQxT+ehrIIseTegTSlGWX2Knt30wzZzhAyJFCqaAIpo7MYVxhFi9/eBimngclp8Drd0GguWvnA++xJTyB0pEdUeOpU4oYne/jF6/s4NF39lIyLIvS4thR5ZSROWzXCWRXb+uWj4MdI0qG5JhIyWDjaq2jUbJTOg6ijdY8q6QONf1bUseprYQcqUd0YK0rXTZnDK9vP0pVUwDO+6EVLb1xd+eOdQegdi9v+6cyNUJ0PC4H379sBpsP1PHB/lquP3tq3J+V1+WkKreMnGC1VUPPABhRMiTE3qdkIiaDjSdQQ4MjtXTwNrTAPu6sn0XJpQFC0j1RAlgybxzBsPK3Dw7C5LNgzlXw5j2dz1myKz6sDZ9AWVQkdNmcsTz21VP57RcW8LlFExKOFRg9DwDdtyaxU+Ew7FwFoWDifoMAI0oGgyFlsgI1NDq7J0o5I8YTVAf+yj1941Qc3D2IlABmjMlj+ug8Hv3nR6gqXPQzyBkJj38OGuzU9vefoNE3mk06KWZ23cemFnHBzFFJI8qCqQvxq5um8rcS9vOvfwwe+ST1L/20259noGFEyZAUNdN3BpucUF2no71TYezwfA5qES1H+nc/jksDhJ3ebt8nInzlzClsO1zP6zuOQc4IuOpR62iKh86Hl74PO19hTdESPC4X44dn99jHmeNHslGnEtjzz4T9KtY/D8CR9/7e47EGCkaUDAkwYmSIIBQkRxvwe1Lbo9TGuGFZVOhItLp/67y5NUC4B5ESwOVzx1oJCy9vt76UlcyHa561Lr79K5i6mEcdl1NanIvTkfr6WjQnjivgPU4gr2oTtDbF7ees3glAccuuQb/Ga0TJkJxB/o/AkCItNThQNKubolSYxS4dQ1Zteb/+LnloJezsmSh5XA6+fUEZ6/fW8Mz7doXz8afAN9bD93YQ/uxfeHd/EzPj7EHqzjjVoxbhJGQVgY2FKkUt1npcHk201AzupAgjSoa4aFuig5oyQwbQJutMJMke0a37RuR62CXj8Qbr+jXLzE0Q7cH0XRtL549n1th8/vvZLVQ22HusHE7ILWbnsUZqmgKcEmcPUncomH4OTeqlZUuXg7gB6+eepw28iZUUcWjXB8c9ZiZjRMlgMKREY80RAFy53RMlEaE6xz4A7+iHve1WbEJBnITRHkZKYB389/+WzqW2KcBNK94nFFEt/7VtVsLDx6YUHberi8rG8lZ4NuFtL8SMJOsqtgBwdPTZANTuH9z7mowoGVLATN8ZoLHaKk7qK+ieKAH4i06wXhzZ2psuxSfYAnBcogQwc2w+P7hsBqu2HuE/n/qAUFgJhZUn1u1jTknBcSU5tDG3pJA1nlPIbj4Ih7vWwavaawn5sBMvIqBOAkd3HveYmUxKoiQiF4vINhEpF5FbYlz3isjj9vXVIjIp4tqtdvs2EbkomU0RmWzb2GHb9BzHGIUiskJEtorIhyLyse79eAyA0SQDAC3VBwDwDRvb7XtHjxlPpeajh/pp6ilk16tz+RL3S4HPf2wSN55byvK1+7jy/rf55mMb2HGkga+eOeW4bQM4HALTLyWgToLvPd7lesvh7QTUycSy2RyUYly1e3pl3EwlqSiJiBP4NXAJMBP4jIjMjOp2LVCtqqXAPcAd9r0zgWXALOBi4D4RcSaxeQdwj6qWAdW27W6PYd/zC+AFVZ0OzAX6ae5gcGHyHAwAwZoDhFTIK+q+KJUV57IhPJXg3iSbRHuJcKtdFug4I6U2vnvhNH5+5VwO1rbw0pZDXH/2VC6bM6ZXbAOcNW8G/wjPIbhhOYRDna45qnexj2LGDc+j0ltCflP/bkLub1KJlBYC5aq6S1VbgeXAkqg+S4CH7dcrgPPE2jW2BFiuqn5V3Q2U2/Zi2rTvWWzbwLZ5RU/GEJF84CzgIQBVbVXVFM43NnTFJDoYQOoPcpRChud3f8qqbFQu68PTcFeX98uhdkF/PQBhd06v2BMRPjW/hLdvWczW/76EWy6Z3q1SS8n42JQiXvEsxtdyxDq1NoKcho845ByLx+WgOXcCxcEDg/qbYiqiNA7YF/G+wm6L2UdVg0AtUJTg3njtRUCNbSN6rO6OMQU4CvxeRDaIyIMiEvM3VESuE5F1IrLu6NH+P4wsUxEzb2eIwNl4mEM6jKKc7kcfpcV5vBueZr2pWNvLnnUl0GyJknpSO2IjVUTkuPYlxcPldDBywRKOaT4tb93XcSEcpsi/n7psq1yRDp9CLs3UVR7sdR8yhVREKdbfQPTTKl6f3mrvyRgu4GTgN6p6EtAIdFkPA1DVB1R1gaouGDlyZKwuQ5tB/K3MkDq+5sNUOYpiHu2djIIsN4fzZhIQd3vduL6ktck6jFC8vStKfcmnFpbySPACfLtfbj9AUI9tJ4sWGofNAMA3qgyAw3u2pM3PviYVUaoAxke8LwEOxOsjIi6gAKhKcG+89mNAoW0jeqyejFGhqqvt9hVYImVIEW3XeyNKBshpPUqjp+df2mZOHMV6mQ3bnu9Fr2ITaGoAwOkbOKI0sSiHj6Z+lhbcBF69HYCq7e8A4Jt4CgBF463TausPbE+Pk/1AKqK0Fiizs+I8WEkFK6P6rASusV8vBVapVTBtJbDMzpybDJQBa+LZtO951baBbfPpnoyhqoeAfSJi56JyHjB4v170IUaSDLQ2kRuux589qscmTho/jGf9c6FqJxzb0YvOdSXQXAuAy3d8FRf6my9dsIAHgpfi3vIk7H4d/4fPc1QLKCmbC8DoidMIqdB6pDzNnvYdSUXJXr+5EXgRK3vtCVXdLCI/EZHL7W4PAUUiUg58B3uaTFU3A09gicELwA2qGopn07Z1M/Ad21aRbbvbY9j3fAP4o4i8D8wDftbdH5ABCBtZGvJUW8VUA/mTemzi5ImFvByab0XgH6xIfsNxELLXlNxZAydSApg7vpCtU7/CRzqa8B8/zdj9L/C8nMHMEqu0k8+XxSFHMe66Pel1tA9J6axgVX0OeC6q7YcRr1uAK+PcextwWyo27fZdWNl50e09GWMjsCDWPYbkdCQ6GFEa6rQe3YkHcBZN7rGNWWMLqHaPZGfeKZRueBTO/nerbE8fEGqxpu/c2QMrUgL4z08u4Nq7b+W28EPUhZ3smPmvuJ0d8UOVZxx5TfsSWBjYmIoOhqSYPAdDg72G4S0u7bENn9vJaVNH8IfWc6CuArb+rZe8i0FLDWEVPFkDT5TGFWbxgy9cxnXyQ36U+yOuv3h+p+tNuRMZFdw/aI+UMaJkiItJdDC00XJkJ1Way6hRo4/LzrknjOSPtSfSWjgVXv1Zl42ivYU0V1JNLtm+3tk829+cXjqCdd8/n3/cdA7jCrM6Xxw+hQIaqT52OD3O9TFGlAwGQ3KqdrJXRzFl5PFtRj13ejEhnLwy+itWcda1DyW/qQc4m6uo0vwepa9nCiISc4Nu1mg7LfyjwZm3ZUTJkJTBOk1gSJ38uh3slvGMzO35URAAJcOyOXXKcG7fOx0tPR/+/sM+KdLq9ldRRR5ZnoErSvEYbqeF1+0fnGnhRpQMyTGiNLRpOEJusIrK3LJeKa1z5fzxfFTVzLo5PwZfPjz6Kajp3XpunpZKKjWffJ+7V+1mAqMmTqdVnYQPbUq3K32CESVDUtSsKQ1t7MrezcOj6zD3jEvnjGFErpd7VjfA5/4M/nr47Xnw0du9Yh9V8vwHOSwj8bgG3yPO7c1ir2sSuZVGlAxDFDGR0pCmZf97AGSVnNgr9nxuJ9efPYW3d1bydtM4uPYl8GTD7y+Bv/5r9zbWhoLw7sMQbO1oaziMO+yn0tP9auYDherCmUzwbyccGnzFko0oGeJiCrIaABp3rqZCR1A6aWKv2fzcoomMH57F95/aRMuwMrj+LTjtG9am2nsXwEMXwVu/gH1roLUpvqH3l8Mz34S//6CjzRa1am9Jr/mbacjYkyiQRvbuGnzJDiltnjUMbYw0DWFUyT64hn+EZ3Lm2IJeM5vlcfKzT57I5x9aw4+f2cLPPjkbufCncNo3rcjnw5VWEgSAOKFwPBSMh8IJ4M0Htw+aq+HDZ60+a34LC74MI09or0J+MHdGr/mbaYwoWwQfwKGtq5lUNjvd7vQqRpQMcdEYrwxDjMqdZAWq2OaZzb/kHV/mXTRnlo3k6+dM5Tev7WRiUTbXnz0Vcovh7JusP3UH4cAG60/VTqjZBztXQWsjBJqtJImxJ8EpX4WVN8Ij/wKffxI+fIZdjkm4cop61d9MYvz0BfjVTfCj1XScgzo4MKJkiEt7npXRpKHLnjcAaBnbpfJXr3DThSewt6qJ25/fSn1LgO9ccELHeUX5Y6w/0z+e3NDVf7FE6deWn4/wNUYXHP9R6JmK0+Nju28GI6veTbcrvY5ZUzIkQO3/Dr7FVENqNG96ln3hkUw+4aQ+se9wCL+4ah5XLRjPr1/dyecfWs2+qgRrSPEYMxe+9jqcdROtF/+c37ecNahFCaBxzCJKQzs5euxIul3pVYwoGeLSnuhgsu+GJq2NePa+zt/D8zmtrO8Ov3Q5Hdz+qRO581Nz2LivhvPu/ge3P7+VygZ/9wwVjIPF36di6jJAGDPIRalwxrk4Rdn57qp0u9KrGFEyxMVM3w1xtr+IM9zKGs+plBX37REQIsKnTxnPqu+ew2UnjuH+f+zktNtX8f2/fkD5kYZu2fqo0oq0xhVm94WrGcOkuWcTUCf+8r4/ybc/MWtKhriYoyuGNqF3/8BhHcGI2ef2SiWHVBhd4OPuq+bxr+dO5bev7+aJtRU8+s5eTp0ynKtPnciFM0cn3RC79ZB1ltIJo/L6w+W04fLlssM3neLKNel2pVcxkZIhARrxX8OQonoPjt2v8XjwbC6Z0//7fUqL87hj6RzeumUxN110AvuqmrnxTxs47fZV3PXiNvbXNMe9d9OBWsYW+CjIHnwlhqKpLzmbE0Ll7N3Xu2Wa0okRJUNcOqbvjCwNOd76JSGc/N13EYsmD0+bGyPzvNxwbimv//u5/O6LC5hbUsCvXyvnzDtW8ZWH1/Lq1iOEIk5GDobCvFV+jFOnDt508EjGzv8EDlF2r34m3a70Gmb6zhAXM303RKndj65/hCdCZ3H+afNwOdP/3dXpEBZPH8Xi6aOoqG7isTV7eXztPl7+8Aglw7L47KIJfHrBeF7afJiapgCXnjgm3S73C6Onn0qN5OPctQq4Id3u9ApGlAxxETN9NzR56fsEFe4PXcHjiyak25sulAzL5qaLpvNv503jxc2H+OPqj7jzhW38vxe3oQoLJw3n3BOK0+1m/+BwsG/Yx5he+Q5N/layvQPzUMNIjCgZ4tI2fWcKsg4hyl+GzU9yX+hTnHHKyYwpyEp+T5rwuBx8Yu5YPjF3LOVH6nly/X7yfG4+/7GJOBz9k5iRCXimX8iIt19kzbo3WHj6eel257hJKS4XkYtFZJuIlIvILTGue0Xkcfv6ahGZFHHtVrt9m4hclMymiEy2beywbXp6OoZ9zSkiG0Tk2dR/LAYLs09pSFF/CH3qeg64J/CgLuGbi8vS7VHKlBbn8e8XT+fr50wl1zu0vmtPWnQZAHUfPJdmT3qHpKIkIk7g18AlwEzgMyISfbDKtUC1qpYC9wB32PfOBJYBs4CLgftskUhk8w7gHlUtA6rpKOzUrTEifPs34MPUfhyGSMz03RAi0AxPXEOopYEvNNzIDRfMHvQVEQYL3oLR7PGeQPHhNwfFKdGpREoLgXJV3aWqrcByYElUnyXAw/brFcB5Ym1sWAIsV1W/qu4Gym17MW3a9yy2bWDbvKKHYyAiJcClwIOp/TgMkUj77/fA/0U3JCAUgCeuQfet5ubg9eSMm8VXzpicbq8M3aBh/LnMCm+j/KN96XbluElFlMYBkZ+0wm6L2UdVg0AtUJTg3njtRUCNbSN6rO6OAfA/wL9D4uJtInKdiKwTkXVHjx5N1HVI0VFmKL1+GPoQfz386SrY8SL3eK/nNdfp3Hf1/IzIuDOkzphTluAUZffqlel25bhJ5Tcv1oph9GMqXp/eau/2GCJyGXBEVZOW0VXVB1R1gaouGDmy72p8DTRMSvggp3oP/P4SdNdr3OW7kd82ncP/fn4+4wozN7nBEJuislOpkQJ8u19OtyvHTSqiVAGMj3hfAhyI10dEXEABUJXg3njtx4BC20b0WN0d43TgchHZgzU9uFhEHk3h8xqiGQTz1IYoNv0F7j+TUNVHfNf1HzzUeCa//9IpLJiUvo2yhuPA4eDAiNOY3byW6vr41S4GAqmI0lqgzM6K82AlFUTHiCuBa+zXS4FVaq24rQSW2Zlzk4EyYE08m/Y9r9o2sG0+3ZMxVPVWVS1R1Um2/VWqenWKPxcDJtFhUFJ3EP78RVjxZY5lT+bC5tt4W05i+XWncuqUoVEFYbCSNesShksDH6x9Nd2uHBdJRclev7kReBEri+0JVd0sIj8Rkcvtbg8BRSJSDnwHuMW+dzPwBLAFeAG4QVVD8Wzatm4GvmPbKrJtd3uMnv5ADB2Y6btBRCgA7/wG7j0F3focTxV+kVMPfpeikjJWfuN05o4vTLeHhuNk4imfIISDps3Pp9uV40IGQwphb7JgwQJdt25dut3ICPw/GoFXAmw87V7mXfj5dLtj6AnhsDVV9+ptUL2bjwpP5WtVn2GPjuLfL5rOF0+bNKQ2mg52dt1xJi3N9Uz7wfp+T1YRkXdVdcHx2jEpNoa4iImQBi7hMGz9G/zvmfDkV6gJuvmu6z84+9A3mFg2mxe/dRZfPmOyEaRBRmDKecxkNx9s3Z5uV3rM0Nr6bOgm9pqSiaYHDkE/vP8EvP1LOLaduqzx/Nz9Hf5w9GROLBnG45+dwSKzdjRoGbdwCWy+hwPvPsNJs6an250eYUTJEBfzHXoA0VIL7/6ftW5Uf5CjOdP4H8e3WF49n5MmjuB3S0s5Z9rIfjusz5AecifMo9Ixgvy9q4Cb0u1OjzCiZIiLmNp3mc+hD2Dtg+j7TyCBJrZln8ztwS/yauVszppWzB/PmcqiycONGA0VRDg6+izm7X+eimO1lIwoSLdH3caIkiEuHWtKCQtiGPqboB+2rIS1D8K+dwg6vKxynckv/OeyV8tYuqiEVadOZMrI3HR7akgDhXMvJe/Ak/xz9UuUXHplut3pNkaUDHEx360zjOo9sP4P6Po/II1HOeYex4Phz/NYy5mMHjWGL5w3kSvmjSNniFXJNnRm9LyLCDzvIrjtJTCiZBhMOMTUvks7rU3w4TOw4RHY8wZhHLzlnM9vW7/MRj2JS+eN43fzx3PyhEIzRWew8OaxL28eZbVv09QaJNszsB7zA8tbQ1pQo0r9iyrsfxc2PIJu+gvir+ewcwyPBK7kyfBZTJl6Akvnl/C/s0aT5XEmt2cYepRdSNn6n/Hme+9xxinz0+1NtzCiZDBkCg1H4L3lhDc8iuPYNlrFy99Ci1geOJtDhSfxqdMm8MTJ4ygZlp1uTw0ZTsmiK2D9z6jc+DcwomQYdJjsu76jtRG2PY++9zi6cxUODfIBZTwW+Apve8/i3PlT+fd5Yzl5wjAzPWdIGU/xNI66xjDi4Guo/mBA/e4YUTIkxUzf9TKhIOx+DX3/ccJbnsUZbOIIRTwVvITnnOdSNmsBS+aN5adTi8y5RoaeIULNuHM5ec8Ktu47wowJo9LtUcoYUTIkRUykdPyowoH16PtPEHz/L7ibj9JANs8GF/E3OYO8srO5/KQSnphejM9t1okMx8+Iky8j66M/sfvdF5kx4QvpdidljCgZkmI06Tio2oW+/wStGx7HW7uLAC5eCZ3EyvDV+CefxyXzJnHf7NHk+9zp9tQwyBg2czEtT3lw7XwFMKJkMAxdqj9CN/+V5o0ryD72PoqwPjSDZ/SrVE26hHPmlHHbrNEMz/Gk21PDYMadxd78BUyvfRt/IIjXPTAe9wPDS0OaMaFSUmr2Ed78FM0bVpBz7D0E2BGewgv6WQ5PuJRTT5rLTTNGMcwIkaEfCZVewIT1b7Nh00ZOOum4T5XoF4woGZKjpsxQTGorCG/+K00bVpB7dAMOYGd4Mi/oZ6mccDELT57P9TNGUZBtpuYM6WH8gktg/Y859sHfwYiSYSCjqqbMUCzqDhD44Cka16+gsHI9DmBPeBIv6GeomvRxW4iKzRqRISPIHTOdSkcRWfvfSrcrKWNEyRCTUCgU8csxxKfvqnbT/P7TNL3/V4qqNuAGDoQn8rAso3bKZcybN5/rpxeTa2rOGTINEQ4VLWTGkTepa/aTn+VNt0dJMf+KDDEJBAJD95dDFQ5vpm7jUwQ3rWR4w3aygF3hifzZtYzmsss5ef5Crp8yHK/LpG8bMhvvtMUUHX2et9f/k9NOPyfd7iRlyD53DIlpbWkmq+3NUAiUwmG0Yg3V7z6Jc9uzFLTsJ1eFdTqNdVlfxjHjEyw6+SSuKyk0R4gbBhTjT74I3rqJ2i2vwGARJRG5GPgF4AQeVNXbo657gT8A84FK4CpV3WNfuxW4FggB31TVFxPZFJHJwHJgOLAe+LyqtnZ3DBEZb/cfjXUg0AOq+ovu/oAGOh+8/CeG7rs9LgAAEcNJREFUTz6RcVNP7NZ9AX9j+2sdrIkOwVYCO/9B5bq/kLPnJfICleSqk7fCs/mw8FPkzPkEZ8ybyb+ac4kMAxhv0UQOucZScPiddLuSEklFSUScwK+BC4AKYK2IrFTVLRHdrgWqVbVURJYBdwBXichMYBkwCxgLvCwi0+x74tm8A7hHVZeLyP227d/0YIwg8F1VXS8iecC7IvL3KL8HPSe++XV4E/iv2m7dF4oQpUFFcw01m16kZsPTFB96jexwI3nq5R96Eh+NvI4RJ32Cs+dM5dx8X7o9NRh6jariU5m9/3mO1TUyIj8n3e4kJJVIaSFQrqq7AERkObAEiHy4LwH+y369ArhXrAqAS4DlquoHdotIuW2PWDZF5ENgMfBZu8/Dtt3fdHcMVf0ncBBAVett2+Oi/B7UBFr99DQHLOBv7ngzkEs6qBI6uoMDa/+KbnuBsXUbKSREWHNZ5VxE1aQLGXfyxzln+rgBd+6MwZAqvmmLyT/wJG9teIMRZ1+cbncSksq/wnHAvoj3FcCieH1UNSgitUCR3f5O1L3j7NexbBYBNaoajNG/J2MAICKTgJOA1bE+oIhcB1wHMGHChFhdBiSNtVUU9vDelqb6iHcDTJSCrTRs/weH1z1N/r5XGBk4wHhga3g8K/OWwrSLmLFgMZeONQfjGYYG40++EF6D5q2rYBCIUqx/tdFPqXh94rXHKn2cqH9PxrBuEskF/gJ8S1XrYvRFVR8AHgBYsGDBAHsCx6epsa7HouRvHljTd1p/mAPrVtKy+TnGVv6TXG3GpW7Wyon8Y/RVFMy9jIVz5zLdbGQ1DEHc+aPY655M0dHMX1dKRZQqgPER70uAA3H6VIiICygAqpLcG6v9GFAoIi47Wors3+0xRMSNJUh/VNUnU/isgwp/Y/fWkSJpberQ74ycvVOlee969q95Cu+ulxnf/CHjgIM6nNd8Z9My+QImL/w4p00ag9NkyxkMVI08lRn7V1BTV09hfl663YlLKqK0Fiizs+L2YyUVfDaqz0rgGuCfwFJglaqqiKwE/iQid2MlIZQBa7Cimy427XtetW0st20+3ZMx7PWmh4APVfXu7v5gBgOtzTEDw5QIN1b1oie9hL+Bw++9SM3GZyg+9A+GhauYosL7lLK+6Mv4Zn2ckxacwSUFWcltGQxDjOxp5+A78BgfbPgHp5x9WbrdiUtSUbLXb24EXsRK3/6dqm4WkZ8A61R1JdbD/xE7yaAKS2Sw+z2BlVwQBG5Q1RBALJv2kDcDy0Xkp8AG2zbdHUNEzgA+D3wgIhttG/+hqs/17Ec18GiLdgLq7HbCQ7ixsuNNGlPC/Ud3sW/1U7D9RSbUvcsogmRpFhvcJ1M7cTGjF3yCeSeUMc9lDsMzGBIx4eQLCL8qNG17FQayKAHYD/Lnotp+GPG6Bbgyzr23AbelYtNu30VHhl5ke7fGUNU3ib3e9P/bu/uoqM47gePfH8OrIgj4EkUjoMiLGlCJ4Dsb0hiTVJM2m7Xds/U03W2zSba77fa06Un3pe2e7qY52b6cTU7WbZLmzUTNbqKbNtsaX1Y3NVoVRAygCL6hgKIoLyIMPPvHfRSKIAMZmGHm9zlnztz7zHOfe+8P7vzm3vvMM0HDfbUJgDZCB5yU3E0Xus0N4/W7Djf1Zbuo3b+FsWe2M7n9JDOAKjOJ7TGrkbR7yViwguUTYodvm5QKAJExCVSGTSe+rtf+Xn5D+8AGMHeLc0+pXQZ+cz+0ucbbm9Mnd1M9p/Y5nRSmXvwdCaaJGOOiyDWLoslfJ27uA2Rn5ZAcrkP6KPVpXJyQy5zqjTQ2NTIm2j/vK2lSCmAdjXUANEn0gHvhjWk5RTUTSKTO+z0djOHyyWLO7HuPyKqtJF0tIQVDvYnhwKiFtKXcQ0reA+RMmaRdtpXyoqjUfCLOvknpwR1kL1vl683plSalQNbsJKWOAZ4pmc5OJrad4nRkGomtdV65BmraWzlduJWGov9mYs1OJnbWEguUkcz28V8iatb9zFmQT/4o/x/FWKmRKnn+3XTsFJrLd4AmJTXcwuwlONeN7yJ75uzxYhJp5Mi4uXBmP2aQ95RaG2qp2vMuHWUfkHz5Y26nlfEmnOKIbA5PfZRJdz5Ixsw00rXLtlLDYlRMPMfCUonz4/tKmpQCWEJLJQChA0xK1b/bSCIQN/szcOY/GEhHh4bqo5zY9SbRJ35LSmspGWKoNXEciC1AZq4kbeH95CbED2h7lFLeUz8+l3ln13O1uZGo0f53X0mTUoC6Ul/LlI4zIODC86TU0niR5Kr1lIRnMfH2NAA6++kRXn+6nJO71xNX9T7J7RVkA+WSwq5JXyYmexWz5i9lWZj+qynlD6Jm5hN+7nVKDm5j9tIHfb05N9F3igBVuuU5cqWTstB0JrqrPVrG3d7G0X9fyx2mgdqClwgNdf49Ojvab6rb3tpM6fY3iDj0BmnXikkASkNS2Tnt60xe9CfMnDmLNO2koJTfSZlfQPtOF81lO0CTkhpKprOTI7vfhT3Pk9t6gP3Rf4R71HgSa0/2u+zRo+W43/lzstuK+b/Uv2VJbgFNl51RHYz72o16rc2XOfLec6Qce4U7uMIpbmPn1MeZsuzPSJ+RQYYmIqX82piYOErDUomr889x8DQpBYC21qsc/p9fkFC8jtmdpzhPHB9Ne5z5a/6Owle/RdgtLt+dqb3A4U0/JP/8ehDYk/Ujljz0BADhEXa4HpuUyj7aTNyH32S+uUBheA7HFz5J9tLPcnuo/hspNZLUj8sl79zrtDY1EBk92GGbh4a+m4xgTVcu8smWn5Jc8RrzucTxkCT2Zv2I7PseZfH1hOIKI5SOm5atv1hP4Ts/Zl71m6yURsoSCpj8yLMsvG36jTph4U73bHFf4+DmfyPr4Pc4HZJI0Wc2kL1ohX6HSKkRKiotn9CaV6ko3E760s/5enP+gCalEeh8dSWVv/4ZGdUbWUALh8OzqV70HFnLHmJ6SI8x4ELCCJVOOjs6CHG5aGm8RPGmfybj5BvcLc2Ux+TB/d8jPX3pTeuRkBCumTBi6/aRevoVSiLmkvzkuyTF+NcnK6XUwMyYV0DbThdN5TtAk5IaDHfbNUr+dxNy8DVmt+wjASiMXsrogm8xZ97yPpcTVzgA7e3XKP1wI1P2/AN5NHBo9CLiVz5N2pwlt1xvG6FkthVTK/EkPbaRGE1ISo14sbGxlISmEVfrf/eVNCn5sfa2Vsr2/IqrxZuZXr+TbC5znjj2Ja5lasHXmD89s/9GXM6fuGjDD8mteoFjrhmcX/EyWQsKPNqGMeL8LHpl+tdYGD9+0PuilPIv9eNzWXLul7Q1XSI8Os7Xm3ODJiU/c7XpCmUfvUfnkS2kXvmIObTQYiIoHZPHyaw1zMl/mIVh4Z43aM+UcqteoDAyj8xvvEdEhOe/N1Q4ahFZzXuYu/qvBrorSik/Fpm6HFfNK1QVbWPGkod9vTk3aFLyA5cvnefY7k24yt8nven3zJU2GoimbGw+YbNXkbF4FfOjRg+qbXF1jXs3cc3PB5SQAFIfW0+j203sINevlPJPM+bfxbVdYTSVbQdNSupCzSkqd28gquLXpLceIkc6qCOeQ+M/S3T2Q6TlrmDBQM6I+hA1YTqUwp4JX2BhUtqAl4+O8Z/TeqWU9ySMjaUoNJ2xtf41Dp4mpWFUc7qCE7vfJqbqA9LbjjBODKdlMvsnf5H4nM+Tmr2MCS7v/mbQnOWf43BoGDl5K73arlJq5LswbgF31LyMu6me0OgEX28OoElpyLW2NFHy4etElbzFrLZD3AZUhiSx9/a/YOLCPyY5PYepPbtxe5GEhDBn6eoha18pNXJFzswnpPYlTh3aRtLiR3y9OYAmpSHTcKGG0s3Pknn6LXJoplomsmfaY0xZ8kVSUrNI8fUGKqWC3sy5y7m6K5zG0u2gSSkwdbjd7H/nWTJLf8ZCucrBUUuIWPIEGbkrSPTypTmllPo0JsTHUhiWSVyN/3xfyaPrRiJyr4iUi0iFiDzVy+sRIrLBvr5XRJK6vfZdW14uIiv6a1NEkm0bx2yb4d5ex1C5XF/LJ8/eTW7Zv3AiMoOqRz5k3rd/xaxF9xGiCUkp5YeuJi4iyV3F+VrPfk1gqPWblETEBTwPrAQygS+ISM9vbX4FuGSMmQH8BHjGLpsJrAFmAfcCL4iIq582nwF+YoxJBS7Ztr29Dq9ruFDDpecLSGs9zL45/8js72wjOfPOoVqdUkp5xeQ7nZ9FP77tFR9vicOTM6UFQIUxptIY0wa8DfS8c74aeNVOvwMUiDNa52rgbWPMNWNMFVBh2+u1TbvMXbYNbJsPenMdnoVlYNqutVL74iomddRw9J5fsuDz30CGsPOCUkp5y7RZeZSFZZJ6dB01Zyp9vTke3VNKBE53mz8D5PZVxxjjFpHLQIIt/7jHsol2urc2E4AGY278fnf3+t5ax01E5KvAV+1sk4jUAxd6q9uvH6wa1GJ+ahyDjUPg0Vh00Vg4Ai8O35/ef53ejQOmeWMTPElKvf0+gfGwTl/lvZ1G3Kq+N9dxc6Ex64B11+dFZL8xJqe3usFE49BFY9FFY+HQOHSxsUjyRlueXGM6A0ztNj8FONtXHREJBWKBi7dYtq/yC8BY20bPdXlrHUoppfyUJ0np90Cq7RUXjtOpYEuPOluAtXb6YWC7McbY8jW251wykArs66tNu8wO2wa2zc3eXIdnYVFKKeUL/V6+s/dvngR+A7iAl40xR0TkB8B+Y8wW4CXgdRGpwDl7WWOXPSIiG4FPADfwhDGmA6C3Nu0qvwO8LSL/BBTatvHyOvqzrv8qQUHj0EVj0UVj4dA4dPFaLMQ52VBKKaV8T/stK6WU8hualJRSSvkNTUrdDPewRL4gIi+LSJ2IlHQrixeRrXZop60iEmfLRUR+buNRLCLzui2z1tY/JiJre1uXPxORqSKyQ0RKReSIiPy1LQ/GWESKyD4ROWRj8X1b7rUhv0YSOyJMoYi8b+eDNQ4nROSwiBSJyH5bNvTHhzFGH859NRdwHEgBwoFDQKavt2sI9nMZMA8o6Vb2Y+ApO/0U8Iydvg/4AOe7YHnAXlseD1Ta5zg7HefrfRtgHCYB8+z0GOAoznBUwRgLAaLtdBiw1+7jRmCNLX8R+Es7/Tjwop1eA2yw05n2uIkAku3x5PL1/g0iHt8E1gPv2/lgjcMJYFyPsiE/PvRMqcuwDUvkS8aYXTi9F7vrPoRTz6GdXjOOj3G+QzYJWAFsNcZcNMZcArbijDs4YhhjzhljDtrpRqAUZySQYIyFMcY02dkw+zB4b8ivEUNEpgD3A7+w894c+iwQDPnxoUmpS2/DKSX2UTfQTDTGnAPnzRqYYMv7iklAxcpedpmLc4YQlLGwl6yKgDqcN47jeDjkF9B9yK+RHoufAt8GOu28x0OfEVhxAOeDyW9F5IA4Q7HBMBwf+ntKXTwZTinYDHRopxFHRKKB/wT+xhhzxfmg23vVXsoCJhbG+W5ftoiMBd4FMnqrZp8DMhYi8gBQZ4w5ICL514t7qRrQcehmsTHmrIhMALaKSNkt6notFnqm1CWYhyWqtafa2Oc6Wx7QQziJSBhOQnrTGPNftjgoY3GdMaYB2IlzX8BbQ36NFIuBVSJyAufy/V04Z07BFgcAjDFn7XMdzgeVBQzD8aFJqUswD0vUfQinnkM7fcn2rMkDLttT9t8A94hInO19c48tGzHstf+XgFJjzL92eykYYzHeniEhIlHA3Tj32Lw15NeIYIz5rjFminEGFl2Ds19/SpDFAUBERovImOvTOP/XJQzH8eHrHh7+9MDpQXIU53r6077eniHax7eAc0A7zqeYr+BcB98GHLPP8bau4PxQ4nHgMJDTrZ1HcW7gVgBf9vV+DSIOS3AuIxQDRfZxX5DG4g6cIb2K7RvP39vyFJw30wpgExBhyyPtfIV9PaVbW0/bGJUDK329b58iJvl09b4LujjYfT5kH0euvx8Ox/GhwwwppZTyG3r5TimllN/QpKSUUspvaFJSSinlNzQpKaWU8hualJRSSvkNTUpKKaX8hiYlpZRSfuP/Ad9CPYQVOoBOAAAAAElFTkSuQmCC\n", "text/plain": [ "
" ] @@ -895,7 +903,8 @@ "source": [ "plt.clf()\n", "# plt.plot(x_part, calcs, '.')\n", - "plt.plot(test_q, calcs_test, label = 'pdf')\n", + "plt.plot(test_q, calcs_test, label = 'pdf (Ctt = 0.0)')\n", + "plt.plot(test_q, calcs_test1, label = 'pdf (Ctt = 0.5)')\n", "# plt.plot(test_q, f0_y, label = '0')\n", "# plt.plot(test_q, fT_y, label = 'T')\n", "# plt.plot(test_q, fplus_y, label = '+')\n", @@ -904,7 +913,7 @@ "plt.ylim(0.0, 1.5e-6)\n", "# plt.yscale('log')\n", "# plt.xlim(770, 785)\n", - "plt.savefig('test.png')\n", + "plt.savefig('test++.png')\n", "# print(jpsi_width)" ] }, @@ -1941,7 +1950,7 @@ }, { "cell_type": "code", - "execution_count": 48, + "execution_count": 47, "metadata": { "scrolled": true }, @@ -2015,7 +2024,7 @@ " \n", " if bo5:\n", " \n", - " if __ < 6:\n", + " if __ >= 6:\n", " \n", " while len(Nll_list[-1])/bo5_set < nr_of_toys:\n", "\n", @@ -2119,17 +2128,9343 @@ }, { "cell_type": "code", - "execution_count": 49, + "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ + "297867.55292633217\n", + "297874.4515031482\n", + "297680.917379759\n", + "297679.2298302753\n", + "297731.38015050907\n", + "297731.5060522116\n", + "297821.62470532436\n", + "297824.8922526447\n", + "297836.00958632847\n", + "297837.03043312504\n", + "298067.41242296295\n", + "298070.4039000074\n", + "297759.57286927546\n", + "297753.0291372624\n", + "297957.1611906972\n", + "297957.17081575457\n", + "297831.26231679344\n", + "297831.36145833845\n", + "297848.0676780384\n", + "297846.2832198446\n", + "297779.8122072425\n", + "297776.32298128755\n", "(22, 1)\n", + "297834.75968782953\n", + "297832.0834866511\n", + "297773.3775115764\n", + "297763.25504734763\n", + "297952.08346605947\n", + "297949.52860720176\n", + "297762.6281981822\n", + "297765.81318548473\n", + "297803.83704359934\n", + "297811.01991119666\n", + "297794.3916452711\n", + "297810.7979379555\n", + "297913.2653391896\n", + "297913.59951744834\n", + "297756.28764621634\n", + "297756.9765937169\n", + "297812.6721880299\n", + "297814.32748209004\n", + "297692.4995896919\n", + "297692.5366929474\n", + "297725.0088581822\n", + "297716.5522611147\n", "(22, 2)\n", + "297891.7868932709\n", + "297891.3358794325\n", + "297684.1496400218\n", + "297689.89588591526\n", + "297840.42868825747\n", + "297838.2073451812\n", + "297807.4771930615\n", + "297788.63515081065\n", + "297924.4682641975\n", + "297924.747263999\n", + "297938.72181570047\n", + "297927.0224916261\n", + "297561.3223710806\n", + "297554.88755021343\n", + "297924.5331074131\n", + "297907.165199243\n", + "298003.9982591958\n", + "297996.3403498225\n", + "297977.19816017954\n", + "297979.3425372678\n", + "297750.34113219613\n", + "297750.7460451668\n", "(22, 3)\n", + "297731.9421160385\n", + "297734.2019179868\n", + "297706.72309247305\n", + "297712.5918348391\n", + "297669.0903500465\n", + "297669.1097966511\n", + "297810.9165841267\n", + "297811.12787400093\n", + "298079.50286133616\n", + "298081.7725297779\n", + "297560.4597656562\n", + "297564.384877007\n", + "297838.2596046878\n", + "297841.32541277003\n", + "297899.34266119305\n", + "297900.03670971974\n", + "297728.8886661879\n", + "297729.0299907548\n", + "297849.1621213897\n", + "297843.24728722055\n", + "297872.4246645974\n", + "297896.55935187754\n", "(22, 4)\n", + "297852.6158331989\n", + "297852.70343575213\n", + "297814.70307739894\n", + "297814.9106343587\n", + "297786.7811010183\n", + "297773.55664862273\n", + "297906.3864541802\n", + "297895.58960884134\n", + "297755.87591917533\n", + "297755.5745460122\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297889.8454083691\n", + "297880.61730811466\n", + "297758.99513447285\n", + "297772.7277769168\n", + "297779.7462599967\n", + "297772.9524078468\n", + "297758.6457573837\n", + "297760.73140441196\n", + "297556.54697834013\n", + "297562.8122389268\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297701.7794438027\n", + "297702.4934702377\n", + "297919.8278118153\n", + "297913.0054556667\n", + "297853.4941586545\n", + "297844.8030402051\n", + "297613.7003851831\n", + "297613.1587532067\n", + "297918.7726800904\n", + "297918.69299575087\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297787.2742605156\n", + "297780.706536736\n", + "297938.77771834214\n", + "297943.8805048078\n", + "297802.0769166769\n", + "297805.80221924535\n", + "297630.92236985406\n", + "297634.20818183484\n", + "297597.04955319385\n", + "297612.7471605604\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297710.82555318816\n", + "297700.6547581145\n", + "297698.276238603\n", + "297701.20106814115\n", + "297654.1104571011\n", + "297656.8669637403\n", + "297905.3797385276\n", + "297914.8283684101\n", + "297594.3733769685\n", + "297592.40463221865\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297790.47600328317\n", + "297794.6402139895\n", + "298063.14545655204\n", + "298062.4787641795\n", + "297742.5854301793\n", + "297741.9619532502\n", + "297869.8253452113\n", + "297871.7013384262\n", + "297688.56062151486\n", + "297690.0607837625\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297915.3138914329\n", + "297912.4466015783\n", + "298026.71860811586\n", + "298026.82736872835\n", + "297901.1278825549\n", + "297893.18077354564\n", + "297809.22549676104\n", + "297820.41223573755\n", + "297788.88445597823\n", + "297789.99420305295\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297832.06855125993\n", + "297839.3724460817\n", + "297828.94031655544\n", + "297829.2922117482\n", + "297820.9674384014\n", + "297826.938151562\n", + "297755.7527015373\n", + "297754.1215906584\n", + "297792.97760426765\n", + "297800.0492997038\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297853.349195588\n", + "297853.1222155888\n", + "297719.9324050648\n", + "297717.88472607004\n", + "297719.60866914626\n", + "297723.7839832492\n", + "298131.75164063676\n", + "298138.08903197304\n", + "297881.0413188011\n", + "297885.6900144825\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297797.45206800936\n", + "297804.7050540202\n", + "297749.91152395704\n", + "297749.8748945173\n", + "297469.79855430697\n", + "297467.22169046995\n", + "297740.89958323614\n", + "297742.2670869287\n", + "297780.6492586394\n", + "297780.0456812219\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297859.40139731\n", + "297851.71129696036\n", + "297945.4190873526\n", + "297938.3301733992\n", + "297687.6245666923\n", + "297683.37556441635\n", + "297730.2862687013\n", + "297736.2419038851\n", + "297937.8581941545\n", + "297923.16214190563\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297882.6944170517\n", + "297882.6035745213\n", + "298036.7007420169\n", + "298030.7092577208\n", + "297804.06371413916\n", + "297809.4535608552\n", + "297661.3744793993\n", + "297663.76479074644\n", + "297792.22832717677\n", + "297792.4921161954\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297717.1517255674\n", + "297717.33032792126\n", + "297714.09908315213\n", + "297715.0244661222\n", + "297692.80019308935\n", + "297711.16511567315\n", + "297739.5881793262\n", + "297722.5116402684\n", + "297902.9549646861\n", + "297903.47638629755\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297822.78725347685\n", + "297826.24923283845\n", + "297654.68808494456\n", + "297641.0529671448\n", + "297883.94099462236\n", + "297881.29538204166\n", + "297627.0044246426\n", + "297615.72111545573\n", + "297987.38132259174\n", + "297988.6235046559\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297687.575159811\n", + "297684.4376705477\n", + "297837.56590441876\n", + "297837.4146166502\n", + "298022.6403591866\n", + "298023.7641792743\n", + "297722.0946554552\n", + "297721.6843467682\n", + "297939.6448343456\n", + "297921.73979955213\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297922.52257591404\n", + "297922.5616259211\n", + "297922.7029678023\n", + "297923.661061408\n", + "297929.41804618546\n", + "297939.1378497065\n", + "297994.60643123416\n", + "297996.6411889125\n", + "297904.1185744967\n", + "297903.6181876099\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297789.46443286317\n", + "297772.8568062482\n", + "297828.8844516927\n", + "297830.2021991758\n", + "297677.2924590585\n", + "297692.9271522497\n", + "297672.10790474975\n", + "297674.782884709\n", + "298033.73361990997\n", + "298034.1385672843\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297953.86561997636\n", + "297945.54380894965\n", + "297832.50763057976\n", + "297848.8223562101\n", + "297738.56790003553\n", + "297722.9263936571\n", + "297934.2679257374\n", + "297935.5056645707\n", + "297732.2173077728\n", + "297732.78390383394\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297914.31295884866\n", + "297928.99183550477\n", + "297884.77416126995\n", + "297884.84945438843\n", + "297744.08359930257\n", + "297744.4566473272\n", + "297903.2835162518\n", + "297903.1400457975\n", + "297998.75490143045\n", + "298000.54243255884\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297510.6547763688\n", + "297511.2177276674\n", + "297969.9418754279\n", + "297996.9421399669\n", + "297853.5919524358\n", + "297856.90122421837\n", + "297694.0693820743\n", + "297703.48131933546\n", + "297737.19172021654\n", + "297737.2219782891\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298042.9802469707\n", + "298059.6743308402\n", + "297846.8726692868\n", + "297836.05601856456\n", + "297784.49429744546\n", + "297781.6101589018\n", + "297927.3238360347\n", + "297925.5456040963\n", + "297606.98541404953\n", + "297609.903620592\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297859.4980172606\n", + "297859.4202610621\n", + "297552.0332016433\n", + "297552.86278484715\n", + "297741.2839640463\n", + "297735.325739854\n", + "297872.66834756016\n", + "297872.0242295439\n", + "297762.67866842175\n", + "297759.8974634638\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297642.7537735527\n", + "297642.56769088504\n", + "298056.5208081159\n", + "298061.5153978158\n", + "297683.0315820724\n", + "297683.10367753584\n", + "297656.59478671005\n", + "297659.60033377045\n", + "297622.9807043862\n", + "297624.5644489547\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297820.89174453926\n", + "297804.88422235835\n", + "297682.55568821385\n", + "297689.87621398206\n", + "297748.92843494617\n", + "297749.5828224214\n", + "297810.0431040116\n", + "297804.26955721935\n", + "297973.6419138905\n", + "297971.8462440953\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297828.54951670574\n", + "297828.74310519104\n", + "297908.13459986774\n", + "297907.2709413057\n", + "297818.2459223969\n", + "297817.81316576333\n", + "297969.7431382599\n", + "297962.90320092917\n", + "298076.94423801743\n", + "298080.1228721196\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297867.08620019787\n", + "297867.96325936605\n", + "297882.5065201261\n", + "297903.241838336\n", + "297990.2635127986\n", + "297993.5890436201\n", + "297950.6274790016\n", + "297933.72835829295\n", + "297864.71174184047\n", + "297865.3068359671\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297924.05056417175\n", + "297924.3462187451\n", + "297839.7484486578\n", + "297858.5148743102\n", + "297833.21209657064\n", + "297831.01548476383\n", + "297894.6787412793\n", + "297897.2072871\n", + "297922.3952885246\n", + "297923.98878231796\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297658.3095291961\n", + "297658.63055961044\n", + "297777.7491475761\n", + "297779.2156469905\n", + "297910.30384963384\n", + "297907.097879856\n", + "297844.44240743655\n", + "297838.1115259306\n", + "297764.31057570333\n", + "297795.12387457775\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297761.47634831123\n", + "297761.6917795783\n", + "297941.54176130757\n", + "297943.7085455759\n", + "297862.37265868345\n", + "297861.01905270666\n", + "297929.8203380249\n", + "297927.75599248166\n", + "297831.79511945735\n", + "297826.8917110866\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298043.062757687\n", + "298043.3331382637\n", + "298105.6560441084\n", + "298106.00267667393\n", + "297864.417196685\n", + "297848.8283173702\n", + "297861.2050438724\n", + "297854.6958583803\n", + "297823.1162213762\n", + "297825.5925257918\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297838.7289526079\n", + "297839.35882420273\n", + "297915.3227840374\n", + "297912.1940105104\n", + "297649.7892491026\n", + "297649.4172037444\n", + "297726.5462085906\n", + "297701.17612640443\n", + "298096.66356244776\n", + "298112.9513885585\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "297898.05075143976\n", + "297898.2402996113\n", + "297748.8200612067\n", + "297753.1076907591\n", + "297803.1027018286\n", + "297805.1745221639\n", + "297772.5932293638\n", + "297772.7292360075\n", + "297835.4308924448\n", + "297832.23978618387\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297724.7729738152\n", + "297742.3134061651\n", + "297681.6278412083\n", + "297687.01138317893\n", + "297851.9826320459\n", + "297852.22497916355\n", + "297874.92179954535\n", + "297867.9264225028\n", + "297836.35849974176\n", + "297838.3784768561\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297781.0767063415\n", + "297794.22053865786\n", + "297796.009713236\n", + "297796.18330437585\n", + "297829.88060681213\n", + "297830.42818558746\n", + "297625.2511861642\n", + "297625.3727447757\n", + "297957.5323682751\n", + "297960.58953196334\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297863.47776986274\n", + "297863.6002848442\n", + "297937.3596542985\n", + "297933.840255488\n", + "298019.80375951505\n", + "298019.8252436238\n", + "297842.2752914994\n", + "297842.42311853304\n", + "297822.5034241884\n", + "297803.0040050677\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297631.28242407565\n", + "297631.2878046075\n", + "297958.1654805185\n", + "297954.7082632855\n", + "297792.1719106659\n", + "297793.0720877706\n", + "297858.2629994951\n", + "297842.7743369887\n", + "297829.30450137856\n", + "297831.9557216867\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297803.6084577795\n", + "297807.8750239341\n", + "297712.66960968816\n", + "297702.44716206886\n", + "297858.95208446035\n", + "297861.30786824465\n", + "297847.8960387496\n", + "297847.8022859622\n", + "297610.37108394643\n", + "297617.2546117072\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297638.92873762344\n", + "297641.2871305943\n", + "298061.4047031107\n", + "298060.2759873658\n", + "297861.48169739783\n", + "297862.9058082386\n", + "297891.78320255043\n", + "297896.7382428553\n", + "297931.3167483972\n", + "297932.4839358871\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297733.2604066564\n", + "297729.6628058305\n", + "297886.093336912\n", + "297889.2382181282\n", + "297757.594626012\n", + "297757.6527060823\n", + "297873.23975737515\n", + "297873.76871830295\n", + "297726.80263460946\n", + "297731.78629800415\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297920.2612742185\n", + "297920.83829701325\n", + "298034.83120646735\n", + "298048.2299261314\n", + "297932.21518371697\n", + "297933.7592507581\n", + "297822.57377405575\n", + "297818.65627642523\n", + "298070.68435055227\n", + "298072.5040657094\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297699.8951478136\n", + "297699.5473202551\n", + "297614.95142979396\n", + "297620.9261126413\n", + "297829.5669325496\n", + "297829.693583697\n", + "297951.8401692653\n", + "297941.66434386646\n", + "297647.21747542836\n", + "297648.5966771582\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297895.00397139374\n", + "297895.9111782473\n", + "297764.09809848916\n", + "297764.30117429903\n", + "297792.2044001613\n", + "297792.3761124163\n", + "297844.4909692462\n", + "297864.3101382638\n", + "297898.2574701485\n", + "297895.6517954243\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297720.0501971487\n", + "297723.875102396\n", + "297875.30939615937\n", + "297876.36063380627\n", + "297710.806410896\n", + "297714.3892934234\n", + "297727.4524255434\n", + "297730.4535277632\n", + "297582.0393226081\n", + "297566.46497548145\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297761.5046900494\n", + "297764.7490371072\n", + "297947.5196054996\n", + "297966.4155373491\n", + "297825.56404743524\n", + "297836.5670601029\n", + "297655.2671071299\n", + "297638.692000991\n", + "297848.28558484156\n", + "297860.24172711244\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297845.7184553577\n", + "297842.7139166549\n", + "297907.6585153427\n", + "297907.6305706452\n", + "297884.1687682717\n", + "297884.25507893745\n", + "297783.9223528222\n", + "297770.2729392441\n", + "297732.16277195537\n", + "297730.6432745445\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297599.13610336615\n", + "297599.5198598796\n", + "297771.1672136519\n", + "297766.5496865282\n", + "298056.0564246288\n", + "298053.9960032627\n", + "297620.2592540829\n", + "297619.5340529829\n", + "297869.3400818468\n", + "297887.0378448166\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298061.68996035785\n", + "298065.86299346713\n", + "297931.9591553534\n", + "297946.64350980986\n", + "297878.9597193362\n", + "297870.7173935257\n", + "297839.9302996106\n", + "297840.051382084\n", + "298163.70930314594\n", + "298176.5435747811\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297763.34828101995\n", + "297761.42321789294\n", + "297883.24605637125\n", + "297881.68512466206\n", + "298023.21497116366\n", + "298021.87869754876\n", + "297663.69980493985\n", + "297664.00662609306\n", + "297862.9492252325\n", + "297862.83022703324\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297844.2168860466\n", + "297848.8237849282\n", + "297856.28409240476\n", + "297854.08661025\n", + "297999.6418975682\n", + "298001.47215317073\n", + "297707.20372629026\n", + "297721.63870624296\n", + "297764.5439354018\n", + "297778.1556733832\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297763.98776783195\n", + "297763.9879069812\n", + "297897.1201530277\n", + "297897.047123692\n", + "297635.6562186534\n", + "297634.58399794303\n", + "297902.4734674841\n", + "297903.83276415186\n", + "297917.7047605667\n", + "297918.2279671679\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297917.885726219\n", + "297934.2618894555\n", + "297945.64006580744\n", + "297946.8266691872\n", + "297762.07738889323\n", + "297762.64653124387\n", + "297829.39076178335\n", + "297829.833231232\n", + "297738.41284378537\n", + "297755.776437026\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297897.18349896255\n", + "297897.85183631117\n", + "297861.2124074388\n", + "297861.2837950142\n", + "297649.8958719653\n", + "297652.835043438\n", + "297612.04859603563\n", + "297606.76777540246\n", + "297715.8149067383\n", + "297719.1663980869\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297634.11135912675\n", + "297634.2516231872\n", + "297775.45731892413\n", + "297783.5592499823\n", + "297924.23618969286\n", + "297925.66103388777\n", + "297847.08334638743\n", + "297846.84432590945\n", + "297698.44787297613\n", + "297694.3918980849\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297756.36631562473\n", + "297756.5079262073\n", + "297761.5854751224\n", + "297773.3176894556\n", + "297931.20176182385\n", + "297936.9931321154\n", + "297947.14021074\n", + "297948.13893039705\n", + "297679.5839404391\n", + "297697.8438848697\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297908.9833638896\n", + "297926.0336710009\n", + "297889.3421375463\n", + "297889.630583656\n", + "297792.09485056106\n", + "297798.73743805505\n", + "297945.142075307\n", + "297945.20979516685\n", + "297835.4800216356\n", + "297835.4048333306\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297738.3714143607\n", + "297736.3026421646\n", + "297802.26752925856\n", + "297821.1047257764\n", + "297670.99821149977\n", + "297668.14289827365\n", + "297666.0975879563\n", + "297666.122451557\n", + "297754.2595767388\n", + "297754.3519273095\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297882.8608586657\n", + "297894.4973780248\n", + "297845.41026423365\n", + "297845.6914489709\n", + "297803.0111419938\n", + "297822.7292277862\n", + "297866.9622386992\n", + "297867.43007297686\n", + "297942.54989219765\n", + "297941.0820206889\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297826.4959450831\n", + "297817.3693548472\n", + "297702.6219398866\n", + "297713.4783082822\n", + "297901.1249808853\n", + "297894.3910650198\n", + "297801.3570715744\n", + "297800.79900949355\n", + "297703.65052121883\n", + "297703.4980426053\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297773.6267731638\n", + "297770.0763191368\n", + "297813.90257430985\n", + "297814.9729592441\n", + "297790.25466407445\n", + "297790.5902774519\n", + "297981.61832675256\n", + "297981.73589373054\n", + "297928.9324508299\n", + "297939.98536165233\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297846.2474318764\n", + "297847.08446573955\n", + "298012.7356823733\n", + "298013.93770551856\n", + "297824.65361278655\n", + "297825.0478620135\n", + "297873.661811089\n", + "297863.54735536885\n", + "297602.55405312456\n", + "297602.58903999877\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297720.2258932136\n", + "297708.64814056235\n", + "297554.11576463946\n", + "297555.0562429484\n", + "297805.32775213284\n", + "297805.7505569598\n", + "297814.30912841536\n", + "297813.96420641145\n", + "297527.61476958735\n", + "297507.82571689796\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297744.8944750389\n", + "297752.5572764146\n", + "297867.59345319215\n", + "297868.0950401822\n", + "297925.95080194646\n", + "297925.68978239136\n", + "297642.87477196805\n", + "297650.1308082583\n", + "297991.2147546851\n", + "298007.1480019213\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "297896.65861246054\n", + "297898.6521094797\n", + "297829.9020195134\n", + "297825.93385869503\n", + "297876.762337011\n", + "297860.47895626223\n", + "297904.61315772764\n", + "297905.51781006006\n", + "297558.51119575265\n", + "297557.92800693243\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297687.89890147065\n", + "297699.33902998606\n", + "297781.68743968796\n", + "297781.0451496604\n", + "297883.2525713439\n", + "297884.1088226877\n", + "297861.6378944409\n", + "297861.41463729175\n", + "297769.2671840808\n", + "297784.59485937137\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297976.689098128\n", + "297976.8186679396\n", + "298145.6207528381\n", + "298144.1072781693\n", + "297897.0571625649\n", + "297902.09681654884\n", + "297863.6369512842\n", + "297862.4119866334\n", + "297731.03226867534\n", + "297749.063414271\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297961.53589032235\n", + "297971.34529862367\n", + "297904.06504263054\n", + "297901.3987015915\n", + "297729.8845593154\n", + "297730.1985598209\n", + "297784.9881160158\n", + "297782.5492824184\n", + "298066.67982962145\n", + "298072.17913357046\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297871.38605204696\n", + "297868.4258186316\n", + "297646.14531230705\n", + "297646.57135574945\n", + "298019.71973484696\n", + "298023.35473194957\n", + "297928.6110733405\n", + "297929.29041992687\n", + "298025.3868489675\n", + "298029.1842907349\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297868.55604500265\n", + "297887.74204212724\n", + "297885.884123033\n", + "297882.80787427863\n", + "297710.1724780721\n", + "297710.9382835373\n", + "297883.1152554287\n", + "297880.75520769286\n", + "297772.5763870355\n", + "297750.39534805977\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297926.4481230032\n", + "297913.79575036536\n", + "297727.14563763293\n", + "297730.7998300827\n", + "297665.358441031\n", + "297649.56670273293\n", + "297753.1240248019\n", + "297757.4007741774\n", + "297903.8835574381\n", + "297906.904865241\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297706.0349979768\n", + "297702.90378543397\n", + "297663.9683274878\n", + "297663.2100499467\n", + "297838.0840943319\n", + "297838.0852257778\n", + "297545.99391675426\n", + "297540.39296673035\n", + "297917.46062217036\n", + "297917.7340259804\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297739.11040793697\n", + "297748.8604471757\n", + "297874.62648449716\n", + "297877.74294658954\n", + "297817.8140005035\n", + "297818.1421472625\n", + "297770.9019357893\n", + "297771.30436574575\n", + "298028.7661432999\n", + "298029.5737986451\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298055.00351035385\n", + "298059.50741409505\n", + "297939.0657979545\n", + "297939.88637977146\n", + "297922.70150164334\n", + "297930.4616394042\n", + "297614.5602649861\n", + "297615.254660011\n", + "297866.4600773866\n", + "297869.77528983256\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297781.3547324874\n", + "297781.4858015065\n", + "297842.3579704628\n", + "297857.9171429128\n", + "297968.63217138255\n", + "297977.761210966\n", + "297833.2057213036\n", + "297814.77888096584\n", + "297935.7904125159\n", + "297935.19888628315\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297794.2612158692\n", + "297786.5228675264\n", + "297877.973001812\n", + "297878.0070832075\n", + "297850.1552344877\n", + "297857.57359471725\n", + "297667.4616924459\n", + "297655.7017891908\n", + "297583.08103305363\n", + "297587.7729388014\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297845.4946897685\n", + "297845.51556934346\n", + "297966.7409238046\n", + "297985.1699576124\n", + "297974.8455615827\n", + "297975.46268317784\n", + "297799.8516351464\n", + "297801.0709198388\n", + "297637.42020948627\n", + "297646.7596610035\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297802.1586174322\n", + "297815.4925651186\n", + "298025.6535787317\n", + "298021.32726186595\n", + "298009.59765698964\n", + "297999.5256107312\n", + "297892.65304843185\n", + "297903.726506478\n", + "297686.6308480092\n", + "297690.4426810438\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297775.9141199661\n", + "297780.1666703935\n", + "297767.5326694222\n", + "297784.65764022217\n", + "297838.4432567785\n", + "297844.1032002577\n", + "297967.76111128414\n", + "297965.287761882\n", + "297641.968956983\n", + "297642.537023734\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298112.0695603679\n", + "298130.7719337607\n", + "297919.82563563454\n", + "297907.28841575666\n", + "297830.20857370057\n", + "297830.2010517363\n", + "297946.16692934925\n", + "297932.78288050904\n", + "297781.724165727\n", + "297770.6454689738\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297896.85141376284\n", + "297896.6919365486\n", + "297872.1453220933\n", + "297861.8977924597\n", + "297942.8971923887\n", + "297945.3769395838\n", + "298017.1443467312\n", + "298004.83742553805\n", + "297914.7373624793\n", + "297930.99257535534\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297661.3290709653\n", + "297661.22477128\n", + "297911.61653266725\n", + "297903.47916451003\n", + "297889.4380020418\n", + "297890.52323713305\n", + "297952.0274184134\n", + "297942.72318106523\n", + "297782.9403028275\n", + "297779.63983385253\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297672.63799146557\n", + "297672.9325050873\n", + "297975.2277838092\n", + "297973.9202212896\n", + "297859.858458503\n", + "297860.51825432706\n", + "297740.83361151186\n", + "297740.5788198606\n", + "297774.08359121846\n", + "297775.0621300614\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297815.8998596835\n", + "297844.1231320192\n", + "297657.9157947293\n", + "297658.9456524875\n", + "297812.739057948\n", + "297814.83207333944\n", + "297915.89783075347\n", + "297920.1103925298\n", + "297847.7202354427\n", + "297848.8066995948\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297838.37529074744\n", + "297840.37167954835\n", + "297924.738756784\n", + "297928.0923666028\n", + "297842.91471606033\n", + "297842.99907053914\n", + "298153.4386093858\n", + "298149.16186638584\n", + "297829.8635000356\n", + "297826.2945352679\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297913.56896919315\n", + "297914.2160045519\n", + "297896.75735601917\n", + "297896.9574688559\n", + "297979.1103061385\n", + "297978.79249400034\n", + "297809.11940677377\n", + "297827.2394747045\n", + "297805.20228635473\n", + "297801.990776467\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297893.4724232474\n", + "297892.5836096623\n", + "297987.9971891473\n", + "297987.3256969925\n", + "297978.7431548544\n", + "297978.6868897267\n", + "297725.56344856485\n", + "297725.79197761003\n", + "297937.12409653934\n", + "297927.4183928653\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297755.59741332516\n", + "297747.2881450187\n", + "297668.6710915893\n", + "297668.6621102662\n", + "297994.72849228006\n", + "297994.80070421123\n", + "297703.98205341335\n", + "297701.4008240913\n", + "297836.6412360007\n", + "297842.36524116475\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297939.6800209376\n", + "297940.0688551013\n", + "297661.6650394511\n", + "297664.12244941405\n", + "297729.14487778436\n", + "297739.5423577342\n", + "297717.58310583263\n", + "297718.6151886075\n", + "297768.32838753593\n", + "297769.1676513854\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297944.80419996416\n", + "297933.66620755027\n", + "297725.17916912533\n", + "297726.1460436844\n", + "297817.03040728805\n", + "297800.1117109785\n", + "297701.3097448169\n", + "297704.9415430642\n", + "297838.58285563986\n", + "297839.3486519452\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297936.5111359809\n", + "297937.72003229713\n", + "297812.98092283326\n", + "297835.97906922136\n", + "297765.5855628131\n", + "297771.13449707464\n", + "297845.86655891663\n", + "297830.1016714152\n", + "297718.4010203126\n", + "297720.5227285703\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297798.1459902977\n", + "297802.9743695282\n", + "297827.8570109278\n", + "297855.77944398683\n", + "297599.08346365235\n", + "297589.61902184604\n", + "297748.60819056985\n", + "297731.84490015166\n", + "297962.31112704444\n", + "297961.98706605757\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298061.970922943\n", + "298075.21868615283\n", + "297897.24406392284\n", + "297889.20318945515\n", + "297951.3058559891\n", + "297946.71510884265\n", + "297845.8875563783\n", + "297846.7416561572\n", + "297729.1785186384\n", + "297719.6242741671\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297836.36454134213\n", + "297836.8977730098\n", + "297865.3499404466\n", + "297873.0291915211\n", + "297841.0831947903\n", + "297838.610614299\n", + "297892.23903632583\n", + "297895.30314881605\n", + "297577.77231854846\n", + "297579.508440022\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297919.7728325539\n", + "297919.77667037747\n", + "297904.62902973616\n", + "297902.5642444517\n", + "297871.51861665084\n", + "297871.4398646512\n", + "297823.06593766564\n", + "297826.2019701843\n", + "297735.18578895275\n", + "297731.6901868873\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298071.0262528217\n", + "298072.84899224143\n", + "297693.23229192384\n", + "297693.23875488166\n", + "297827.8008878479\n", + "297842.54166812875\n", + "297609.32280515454\n", + "297616.0424853872\n", + "297604.5024973791\n", + "297606.5036591655\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297765.9174489037\n", + "297768.3872530274\n", + "297949.0687232777\n", + "297949.8426594391\n", + "297643.7620520645\n", + "297639.974656434\n", + "297907.0725408558\n", + "297904.48754232307\n", + "297836.4402389001\n", + "297853.0073809671\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297581.9959966746\n", + "297582.64232667815\n", + "297839.8572013256\n", + "297840.6459988273\n", + "297877.98713869305\n", + "297877.78887215967\n", + "297831.8816478041\n", + "297832.05066899257\n", + "297891.8051069352\n", + "297892.0988863816\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "297876.21625240357\n", + "297876.66973067867\n", + "297843.1798801997\n", + "297845.8258768632\n", + "297890.3568199211\n", + "297890.3743734303\n", + "297976.68280174985\n", + "297989.58033397415\n", + "297948.8172265709\n", + "297949.4008266451\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297695.9218228974\n", + "297696.1057719577\n", + "297741.0218046947\n", + "297746.1172987372\n", + "297772.4518119021\n", + "297764.4152713146\n", + "297687.20516323706\n", + "297681.290993458\n", + "297922.53912294965\n", + "297925.8150263367\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297857.138977586\n", + "297846.3013262979\n", + "297667.4263899831\n", + "297667.371812501\n", + "298160.03778631333\n", + "298160.6255061958\n", + "297757.0984516159\n", + "297740.7061624998\n", + "297834.2132303334\n", + "297833.7522325814\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297887.9954247301\n", + "297890.91604286723\n", + "297989.724978243\n", + "298010.35012290225\n", + "297848.09653182904\n", + "297849.36456548166\n", + "297811.8581823415\n", + "297811.98926870816\n", + "297881.93239248195\n", + "297892.99661780964\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297998.92633183807\n", + "297993.6054547735\n", + "297847.38262977067\n", + "297847.28239292547\n", + "297899.2653882434\n", + "297895.7042503484\n", + "297762.8013702762\n", + "297766.51242801576\n", + "297734.7249219975\n", + "297734.00843078375\n", + "297655.7129904571\n", + "297657.2409418409\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297860.7474643973\n", + "297861.1211964939\n", + "297883.3258275599\n", + "297883.6986821977\n", + "297809.9000097115\n", + "297814.23073542287\n", + "297748.6102404877\n", + "297748.25980403996\n", + "297766.77412838547\n", + "297765.99496990157\n", + "297973.9966459824\n", + "297986.81705962186\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297576.04872260435\n", + "297579.67786620936\n", + "297797.5824461499\n", + "297798.51803312585\n", + "297928.7945800067\n", + "297929.2405150713\n", + "297959.5495842775\n", + "297960.66004641954\n", + "297872.32737549907\n", + "297871.2921875425\n", + "298048.0389874534\n", + "298067.53691733006\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297842.86176540237\n", + "297841.6319377567\n", + "297689.283875228\n", + "297692.68475665\n", + "297705.21444822435\n", + "297697.0544662373\n", + "297960.0553681638\n", + "297960.84923091804\n", + "297922.29409089213\n", + "297925.2372341377\n", + "297705.8981705055\n", + "297712.6551850806\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297853.8547228897\n", + "297854.82008339156\n", + "297802.64408099983\n", + "297796.86685022345\n", + "297782.49421856186\n", + "297797.5876298519\n", + "297896.76713897643\n", + "297897.1354176632\n", + "297859.4817129832\n", + "297860.97751692263\n", + "297807.356050944\n", + "297802.92818769696\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297561.06195776805\n", + "297579.2210256559\n", + "297638.84198066505\n", + "297638.9032305268\n", + "297748.17020630004\n", + "297743.0235659946\n", + "297724.7281500199\n", + "297721.5895289746\n", + "297845.2557001553\n", + "297847.41448102583\n", + "297981.068421349\n", + "297980.6181475907\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297680.09172055346\n", + "297683.59277520556\n", + "298086.69289958273\n", + "298090.6226207017\n", + "297847.79099038686\n", + "297847.92124445323\n", + "297780.520137805\n", + "297775.23175482306\n", + "297694.44580601004\n", + "297694.5706148669\n", + "297831.6267446286\n", + "297832.6526595628\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297873.5066221678\n", + "297861.180158759\n", + "297922.17422039725\n", + "297925.7570404019\n", + "297750.160399186\n", + "297740.34432174923\n", + "297998.00915983744\n", + "297994.8784451324\n", + "297697.7162304613\n", + "297694.61151108466\n", + "297752.25697422604\n", + "297729.12982429116\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297673.72864244215\n", + "297656.40037956665\n", + "297801.40787430486\n", + "297802.2922545255\n", + "298002.063967792\n", + "298002.16802967904\n", + "297876.30647292075\n", + "297877.18443038233\n", + "297959.82665867836\n", + "297956.8161006005\n", + "297959.7592103044\n", + "297959.38944828726\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297781.21573480265\n", + "297781.3342680196\n", + "297910.3365698998\n", + "297910.916086064\n", + "297775.3554677568\n", + "297776.0123889034\n", + "297743.6771377628\n", + "297743.8835650943\n", + "297817.41107523086\n", + "297819.8628977235\n", + "297831.84061724856\n", + "297833.3192544768\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297790.4377838044\n", + "297790.88446993125\n", + "297755.5966408482\n", + "297755.0416262463\n", + "298048.789993925\n", + "298052.67275731184\n", + "297813.87355566036\n", + "297814.4063904674\n", + "297823.24734071724\n", + "297821.7250597579\n", + "297862.69545930554\n", + "297866.32510008226\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297808.72376661183\n", + "297807.9910254681\n", + "297797.9474647148\n", + "297798.08469985053\n", + "297794.6222683874\n", + "297790.06007872\n", + "297862.09035796556\n", + "297865.241738838\n", + "297858.09483480756\n", + "297858.1523273602\n", + "297771.85808570805\n", + "297775.95192204294\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297749.71413954877\n", + "297749.605902398\n", + "297855.93096922094\n", + "297862.63339594554\n", + "297918.46732813993\n", + "297919.5560326019\n", + "297969.45505966054\n", + "297969.70745880215\n", + "297848.08602035174\n", + "297833.1407417858\n", + "297953.1117774911\n", + "297947.38240396796\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297936.5736278822\n", + "297936.5935071962\n", + "297806.13562636165\n", + "297807.2259258525\n", + "297748.21911943576\n", + "297748.7195222255\n", + "297737.7344802567\n", + "297752.8149874141\n", + "297809.0888933791\n", + "297810.08207026136\n", + "297800.04847978574\n", + "297810.0859539438\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297695.7728485537\n", + "297696.4977524983\n", + "297899.0359612446\n", + "297917.7694098076\n", + "298009.35675947176\n", + "298020.377075969\n", + "297815.51012973103\n", + "297814.5656638856\n", + "297891.308567538\n", + "297891.5554009128\n", + "297901.4551099691\n", + "297906.0516532523\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297918.1673547899\n", + "297913.56254950224\n", + "297935.5703381943\n", + "297951.6233557166\n", + "297783.80520006095\n", + "297798.75730614446\n", + "297612.0398443479\n", + "297613.3291131576\n", + "297834.0155689172\n", + "297826.083565172\n", + "297668.5555528975\n", + "297659.3724711308\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298062.5526898503\n", + "298070.05003009114\n", + "297840.560384095\n", + "297840.9687500967\n", + "297980.7343671657\n", + "297992.7276494553\n", + "297958.04470353224\n", + "297956.0330188281\n", + "297794.7820002769\n", + "297780.9204643162\n", + "297863.6843748138\n", + "297861.4437513321\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297782.5861148363\n", + "297782.73302925494\n", + "297833.1397723003\n", + "297812.6865989643\n", + "297718.8368634225\n", + "297718.8413624155\n", + "297956.65424749197\n", + "297973.318475322\n", + "297863.9946761113\n", + "297849.5393111566\n", + "297928.1174923579\n", + "297918.6740095459\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297937.52031398454\n", + "297951.0604031749\n", + "297945.0156073182\n", + "297955.147028284\n", + "297833.2338153373\n", + "297832.76604300505\n", + "297691.0132919424\n", + "297685.36174073745\n", + "297849.0243249142\n", + "297849.2669035868\n", + "297730.181330317\n", + "297719.181463452\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297731.85629608546\n", + "297733.8239776823\n", + "297690.3729423603\n", + "297694.84207067045\n", + "297770.4396910505\n", + "297770.45994113525\n", + "297900.8846429061\n", + "297901.3181019804\n", + "297803.25009851996\n", + "297801.0280959925\n", + "297742.97371524165\n", + "297747.91975919105\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297890.35469582933\n", + "297887.921232057\n", + "297960.96479349583\n", + "297940.3530237617\n", + "297985.457398781\n", + "297985.7411436288\n", + "297693.4749499704\n", + "297704.7532593999\n", + "297834.2639044472\n", + "297819.2833748253\n", + "297727.6193932271\n", + "297733.870641231\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297765.8582294376\n", + "297765.8757109611\n", + "297784.25099515787\n", + "297778.6189465915\n", + "297887.32207721454\n", + "297898.1509948005\n", + "297931.09616622294\n", + "297932.3912720585\n", + "297873.6667089317\n", + "297874.7549893983\n", + "297872.15361573204\n", + "297873.1123407287\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297859.28814382484\n", + "297860.6054810841\n", + "297851.4870198728\n", + "297862.6705393715\n", + "297771.6068465028\n", + "297770.4384898724\n", + "297820.7473449027\n", + "297821.29761797143\n", + "297748.8906762401\n", + "297729.99903035274\n", + "297774.4065764861\n", + "297771.7279087483\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297834.574816812\n", + "297834.0776321232\n", + "297893.23283133906\n", + "297878.5198309322\n", + "297982.50404133846\n", + "297984.7691935891\n", + "297972.36790030875\n", + "297975.54110858514\n", + "297728.22061474284\n", + "297753.43047190935\n", + "297714.1788920942\n", + "297732.7883058196\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297852.3380192534\n", + "297846.76394536236\n", + "297908.85622601805\n", + "297907.70365853386\n", + "297820.5199255557\n", + "297814.90917350375\n", + "297944.03689407074\n", + "297943.173041374\n", + "297987.48221260397\n", + "297987.7525193231\n", + "297763.0825387522\n", + "297761.32794270915\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297666.69180361554\n", + "297668.49124032626\n", + "297864.1706252677\n", + "297865.3904730151\n", + "297745.2482393467\n", + "297730.3475722076\n", + "297765.53852734726\n", + "297766.6198084574\n", + "297894.6021980384\n", + "297888.0619071807\n", + "297946.8995343555\n", + "297948.71025467047\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297578.9411478247\n", + "297591.465185624\n", + "297787.18983725813\n", + "297787.2486846933\n", + "297643.45448197436\n", + "297645.9920056064\n", + "297790.1115273566\n", + "297794.00150259363\n", + "297837.6879204043\n", + "297828.3069691\n", + "297935.25297458796\n", + "297935.47123480565\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297750.35927925527\n", + "297727.179810655\n", + "297680.2884548605\n", + "297693.99148042605\n", + "297714.6636053158\n", + "297710.8845580326\n", + "297853.5623193891\n", + "297858.0040085418\n", + "297909.9313966611\n", + "297909.2026104167\n", + "297849.6197052197\n", + "297866.74195935065\n", + "(22,)\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297871.3280851183\n", + "297885.3347758578\n", + "297917.06554210867\n", + "297906.20141349\n", + "297990.8894913383\n", + "297989.06608820526\n", + "297794.0634010416\n", + "297794.63342159695\n", + "297781.0617665989\n", + "297782.7429510442\n", + "297981.20872407034\n", + "297982.0481241388\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297647.490539234\n", + "297648.3423315904\n", + "297725.4877598449\n", + "297725.8370599051\n", + "297768.59556602285\n", + "297765.81625121745\n", + "297937.3423409506\n", + "297937.46874179976\n", + "297844.4203164035\n", + "297821.5176080791\n", + "297823.7525104407\n", + "297821.21943339665\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297704.5124378742\n", + "297705.63148911204\n", + "297882.9266309914\n", + "297882.9389224528\n", + "297581.5251810384\n", + "297600.42808948114\n", + "297743.2499194651\n", + "297739.65430250746\n", + "297801.3072646391\n", + "297801.22490832093\n", + "297899.40198200784\n", + "297911.1813638174\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297914.0529099698\n", + "297914.34695983294\n", + "297769.6706226494\n", + "297769.7897929402\n", + "297848.64758265344\n", + "297839.2930163581\n", + "297811.57065845066\n", + "297815.14387728163\n", + "297759.43899990537\n", + "297760.53124889435\n", + "297721.9760609115\n", + "297737.46967625496\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297796.0381978092\n", + "297799.287748535\n", + "297842.05207657017\n", + "297842.85910106683\n", + "298021.30287944205\n", + "298021.8624634523\n", + "297862.8702408879\n", + "297855.9542179459\n", + "297830.74241098063\n", + "297853.223962468\n", + "297707.18867335515\n", + "297706.7595396543\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297613.2117278085\n", + "297613.21142874804\n", + "297609.9674603302\n", + "297610.0899599388\n", + "297744.2339718751\n", + "297744.5334648237\n", + "298194.91832275037\n", + "298195.48963592923\n", + "297952.33510232996\n", + "297960.91686758026\n", + "297957.0967617338\n", + "297946.61670228204\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297814.06574384205\n", + "297812.82810458454\n", + "297904.70248428517\n", + "297922.25523558265\n", + "297601.7377933655\n", + "297582.91444713017\n", + "297752.0778533675\n", + "297753.0219045244\n", + "297697.9699053583\n", + "297700.26244631264\n", + "297786.78298987163\n", + "297786.4051738795\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297725.0210466601\n", + "297717.239896274\n", + "297896.5291990386\n", + "297896.80966234254\n", + "297815.4389946376\n", + "297830.9192728775\n", + "297901.9172996545\n", + "297893.93691274675\n", + "297780.2976769269\n", + "297792.7959747117\n", + "297645.18405550485\n", + "297650.9295305475\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297784.50909979385\n", + "297786.01666950015\n", + "297779.3479023417\n", + "297787.9091416878\n", + "297644.5029239654\n", + "297637.36437116336\n", + "297684.4443430308\n", + "297683.5492726078\n", + "297663.05395569134\n", + "297661.4271094721\n", + "297712.5330420775\n", + "297713.9103818162\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297645.4923042488\n", + "297645.57531334733\n", + "297823.46438624075\n", + "297816.074483915\n", + "297690.087269828\n", + "297693.18266193464\n", + "297869.1911366629\n", + "297887.1674322009\n", + "297968.5236510901\n", + "297968.5199932973\n", + "297674.5429118708\n", + "297679.1188228369\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297666.2941080295\n", + "297668.9681893078\n", + "297854.19992273994\n", + "297851.29559007776\n", + "297769.6525451397\n", + "297767.42376279045\n", + "297759.98332038417\n", + "297755.29310936865\n", + "297869.88164329313\n", + "297870.1917923032\n", + "297912.2156459956\n", + "297894.217066052\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298010.0395950116\n", + "298011.1664089652\n", + "297894.12016857124\n", + "297894.3208763346\n", + "297668.76881648524\n", + "297671.14071563416\n", + "297889.5072528391\n", + "297879.45522131183\n", + "297759.9065900288\n", + "297760.8741640695\n", + "297681.4504373437\n", + "297683.3149985952\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297733.9665638409\n", + "297728.8193864339\n", + "297886.92546481144\n", + "297888.19342324015\n", + "297801.6891713702\n", + "297806.65546096256\n", + "297949.1759210486\n", + "297953.99661868555\n", + "297963.9928201682\n", + "297963.90853034536\n", + "297752.1972564933\n", + "297755.91240151005\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298008.9621848522\n", + "298008.67158710596\n", + "297739.92378314096\n", + "297726.5862288946\n", + "297742.0601466974\n", + "297742.7383872864\n", + "297906.75839737465\n", + "297901.32581503957\n", + "297733.3147495153\n", + "297746.8406627429\n", + "297824.7635933407\n", + "297829.84112003486\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297884.2932778301\n", + "297889.93397244596\n", + "297856.39112635405\n", + "297840.2732660534\n", + "297826.4463073311\n", + "297810.05969405116\n", + "297861.2464032161\n", + "297861.5342189207\n", + "297783.3181079512\n", + "297786.8625061824\n", + "297701.5158222667\n", + "297703.25336036924\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297707.151750481\n", + "297711.35044123145\n", + "297818.2089378189\n", + "297834.4289778676\n", + "297834.49982269143\n", + "297835.3320828085\n", + "297815.5851829715\n", + "297816.0938928619\n", + "297909.90925843903\n", + "297912.6917244799\n", + "297743.48806175514\n", + "297741.0604543642\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297897.32670829236\n", + "297890.76553282916\n", + "297651.88608147\n", + "297651.75667492417\n", + "297897.09429972694\n", + "297898.1998198527\n", + "297788.1444083755\n", + "297790.1174995157\n", + "297645.8947619591\n", + "297647.5531264208\n", + "297664.3271573283\n", + "297666.1605412518\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297903.21484316647\n", + "297893.61478575406\n", + "297895.061305719\n", + "297908.54771719547\n", + "297882.57014204125\n", + "297865.5107640313\n", + "297941.75109853246\n", + "297943.18580559315\n", + "297713.72781279124\n", + "297714.0775794855\n", + "297772.21193620196\n", + "297774.93066917727\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297826.2738166504\n", + "297819.37747229973\n", + "297794.0619788505\n", + "297794.2810564108\n", + "298024.0810513804\n", + "298024.8719058002\n", + "297847.28245698096\n", + "297848.41930355324\n", + "298030.2329676259\n", + "298030.24531630654\n", + "297719.04683378077\n", + "297707.0915484613\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297875.21799840865\n", + "297876.41677623463\n", + "297610.4695353811\n", + "297622.3461556909\n", + "298035.9827901676\n", + "298035.22759150557\n", + "297877.5025939944\n", + "297875.1087344977\n", + "297875.9962863828\n", + "297863.718352394\n", + "297875.96724951285\n", + "297872.5083929872\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297694.60730957316\n", + "297695.9429977275\n", + "297733.40327072685\n", + "297724.17071745626\n", + "297875.4220639783\n", + "297874.8623381968\n", + "297745.04478542967\n", + "297744.360076775\n", + "297643.6737928637\n", + "297643.10605981783\n", + "297557.9336116269\n", + "297554.3146342767\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297702.71176875586\n", + "297707.90884056\n", + "297719.2779729795\n", + "297720.0042753865\n", + "297807.62353648903\n", + "297805.6833666052\n", + "297793.22863037884\n", + "297792.08119768347\n", + "297752.92691092356\n", + "297754.18235750124\n", + "297754.7355722178\n", + "297753.6936558077\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297577.4253921686\n", + "297577.04448628955\n", + "297836.02127838944\n", + "297834.1124987035\n", + "298009.57277781796\n", + "298028.3387749532\n", + "297782.1753294695\n", + "297784.6499494361\n", + "297760.3752412872\n", + "297762.0518583465\n", + "297717.9331756615\n", + "297716.9277071917\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297827.4464285282\n", + "297827.26379117125\n", + "297699.75313293014\n", + "297706.3671692366\n", + "297885.7203478873\n", + "297892.5316712578\n", + "297810.628153303\n", + "297808.091665164\n", + "297868.3439426073\n", + "297862.25508579204\n", + "297853.4471167468\n", + "297855.280309862\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297863.65944803774\n", + "297884.3253670319\n", + "298137.333492319\n", + "298139.81712983554\n", + "297858.33807965985\n", + "297858.34685023164\n", + "297927.6079730558\n", + "297940.83541724185\n", + "297730.9642472171\n", + "297736.06282005884\n", + "297803.02203569474\n", + "297821.90203485097\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297679.9227137118\n", + "297680.18992211064\n", + "297802.79039505945\n", + "297803.068998836\n", + "297658.2335108294\n", + "297667.4175371853\n", + "297880.08453463565\n", + "297894.10097695555\n", + "297853.9735823088\n", + "297854.58037285984\n", + "297807.9330424313\n", + "297807.92512048397\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297747.7313138291\n", + "297746.60575922613\n", + "297970.11838977644\n", + "297946.9064650577\n", + "297743.7039665572\n", + "297725.04883652594\n", + "297933.92606354627\n", + "297933.765292799\n", + "297705.84128237364\n", + "297701.8750628082\n", + "297801.4744902421\n", + "297801.50373548747\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297748.83314222546\n", + "297751.17821688013\n", + "297755.66751665145\n", + "297759.51220206707\n", + "297832.08876348945\n", + "297857.8040817775\n", + "298035.2875965297\n", + "298052.787543967\n", + "297697.3847850009\n", + "297707.3505917281\n", + "297735.56588707183\n", + "297736.0972676654\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297696.84070947417\n", + "297695.56302475557\n", + "297893.9514228982\n", + "297893.8590284761\n", + "297799.7058968983\n", + "297802.0898840804\n", + "297872.9311410535\n", + "297876.2191820954\n", + "297723.5112533522\n", + "297723.7564081292\n", + "297582.7676099444\n", + "297580.67566387117\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297804.1137211474\n", + "297799.9658863748\n", + "297917.1668791836\n", + "297917.4257697943\n", + "297723.90822505933\n", + "297709.8295645201\n", + "297865.5468287738\n", + "297867.6074985258\n", + "297853.47744609445\n", + "297839.28882075293\n", + "297852.18324511277\n", + "297852.52812590357\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297686.1666539073\n", + "297696.0531399551\n", + "297778.4233253013\n", + "297779.04528155207\n", + "297845.2893010541\n", + "297846.1648427153\n", + "297663.95354006026\n", + "297662.85588961444\n", + "297821.82164740365\n", + "297816.5349418472\n", + "297873.0453486248\n", + "297870.3430726534\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297693.72663840966\n", + "297693.13165357173\n", + "297830.93506274157\n", + "297833.05055871385\n", + "297842.7061828181\n", + "297832.28321501723\n", + "297903.7548765918\n", + "297903.70723998087\n", + "297806.41268004815\n", + "297795.28365554777\n", + "297815.83957286784\n", + "297838.3956408161\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298124.793352484\n", + "298111.86716953764\n", + "298023.0220341562\n", + "298013.1569130689\n", + "297477.3974453441\n", + "297464.667134059\n", + "297647.68989511504\n", + "297639.9608289245\n", + "297797.11522474076\n", + "297797.8859221341\n", + "297879.3298606291\n", + "297879.5474411032\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297939.7744067642\n", + "297944.8594608057\n", + "297884.85900939704\n", + "297903.84015536594\n", + "297948.43582982005\n", + "297947.17869033257\n", + "297795.08096311905\n", + "297792.7023896548\n", + "297938.7087655722\n", + "297934.95490087336\n", + "297719.35897609586\n", + "297719.4001943639\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298000.2171890136\n", + "297984.1514819742\n", + "297680.9057466849\n", + "297680.98769873823\n", + "297787.4578760335\n", + "297774.13451296533\n", + "297917.2553771378\n", + "297917.27733999415\n", + "297735.41186664946\n", + "297739.9990636839\n", + "297726.9494474326\n", + "297719.7954865699\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297910.0641097936\n", + "297896.46108855074\n", + "297751.13747901615\n", + "297751.0852871497\n", + "297750.5514317199\n", + "297748.2438053241\n", + "297709.08095756633\n", + "297722.7071774194\n", + "297791.78559924336\n", + "297791.88054482295\n", + "297879.5625047981\n", + "297879.77780598565\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297892.96347452764\n", + "297896.17005487124\n", + "297624.91403866\n", + "297635.22468215757\n", + "297771.8437488879\n", + "297767.8522172677\n", + "297759.7463536275\n", + "297757.89925293735\n", + "297646.0563436954\n", + "297644.304231759\n", + "297958.5596923978\n", + "297981.9406115753\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297900.65896508907\n", + "297899.52164172026\n", + "297566.88377406483\n", + "297565.01174881635\n", + "297845.92376234895\n", + "297846.0950879673\n", + "297891.7493974077\n", + "297887.7888278667\n", + "297733.4152778671\n", + "297729.14039450954\n", + "297961.29908948066\n", + "297954.7374273766\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297827.2887579214\n", + "297829.8775261807\n", + "297907.6207180734\n", + "297907.944110982\n", + "297861.4408451627\n", + "297875.2474821996\n", + "297683.6169232604\n", + "297668.97134225507\n", + "297540.5211705067\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "297540.85942056804\n", + "297973.2470724557\n", + "297973.31553616177\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297972.27692748565\n", + "297972.20025232626\n", + "297823.8448134473\n", + "297825.36500938126\n", + "297829.8569049761\n", + "297833.55503908294\n", + "297661.0017076949\n", + "297661.04735390487\n", + "297759.80626757286\n", + "297743.279671882\n", + "297766.6108305773\n", + "297752.67793123494\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297868.46554995637\n", + "297872.49542966986\n", + "297844.34037414106\n", + "297843.48647625896\n", + "297871.14093382703\n", + "297882.4287370263\n", + "298052.6255938491\n", + "298053.48468706175\n", + "297887.4902703283\n", + "297869.1506443863\n", + "297884.09240948997\n", + "297885.50566935685\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297933.046622954\n", + "297936.2672948495\n", + "297654.47620940726\n", + "297668.23188946745\n", + "297921.4456873579\n", + "297906.5344555925\n", + "297732.28192141623\n", + "297732.62294185435\n", + "297665.6385215139\n", + "297672.3503296462\n", + "297813.7152152668\n", + "297818.9681907603\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297724.42356298317\n", + "297739.5313307383\n", + "297761.6461894062\n", + "297746.51921802346\n", + "297750.9090938311\n", + "297749.5831183744\n", + "297885.52057789656\n", + "297886.1316004333\n", + "297887.18293500156\n", + "297887.1837216377\n", + "297595.5898080501\n", + "297597.1473281789\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297945.7088981396\n", + "297961.293996574\n", + "297829.92614382954\n", + "297831.00518358964\n", + "297662.2572131864\n", + "297669.1090070812\n", + "297714.8409502319\n", + "297690.7599277831\n", + "297838.15109529643\n", + "297821.806390444\n", + "297953.02994580223\n", + "297947.7447457269\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297716.8874574668\n", + "297713.24846932915\n", + "297870.22502283123\n", + "297875.1505254192\n", + "297680.364661621\n", + "297680.4877096464\n", + "297989.9548142187\n", + "297969.2149471177\n", + "298212.0811159218\n", + "298211.9368565521\n", + "297792.8541416513\n", + "297788.3839622181\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297800.68363675656\n", + "297807.732663498\n", + "297872.94884881773\n", + "297891.0299653657\n", + "297651.9093683522\n", + "297639.21603786375\n", + "297709.9705337879\n", + "297709.9716184969\n", + "297984.3166465985\n", + "297984.4700809414\n", + "297879.8076050199\n", + "297899.60102482775\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297901.2204942531\n", + "297905.8351516773\n", + "297767.02825854754\n", + "297772.94746569276\n", + "297737.4016823729\n", + "297722.4553455085\n", + "297875.32191640977\n", + "297875.1304039607\n", + "297630.28154116095\n", + "297629.25460770814\n", + "297775.5485605218\n", + "297789.40907294874\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297979.52793261484\n", + "297979.5919330694\n", + "297865.5896136987\n", + "297866.90086189366\n", + "297755.08963847195\n", + "297754.7053600217\n", + "298013.92452744744\n", + "298014.66796812066\n", + "297798.97175975546\n", + "297799.011031621\n", + "297755.69244514045\n", + "297755.47459893156\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297804.2547942451\n", + "297810.1957616427\n", + "297960.2896326768\n", + "297961.1698465836\n", + "297690.384044723\n", + "297695.2751410582\n", + "297773.23879494675\n", + "297773.3724615106\n", + "297749.0374015433\n", + "297749.92804553447\n", + "297726.46207920986\n", + "297714.3848109481\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297802.85698832275\n", + "297804.6240171495\n", + "297778.8777626014\n", + "297779.68602781463\n", + "297977.2775975664\n", + "297977.2798103108\n", + "298181.6737278043\n", + "298197.28507257125\n", + "297732.32694852963\n", + "297753.4624063391\n", + "297876.181672194\n", + "297876.2133866994\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297735.6530525269\n", + "297738.0739511385\n", + "297933.6734540498\n", + "297933.788369366\n", + "297837.38475046493\n", + "297846.39151878445\n", + "297778.6350558658\n", + "297765.48518659535\n", + "297902.40687305504\n", + "297902.7610668156\n", + "298047.572381533\n", + "298026.4272708351\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297697.8473434882\n", + "297698.91993046534\n", + "298059.09178462584\n", + "298067.21823141014\n", + "297936.00316850684\n", + "297939.9952969336\n", + "298143.6097435646\n", + "298146.9592107111\n", + "297871.24361002044\n", + "297872.29025410785\n", + "297818.77258155076\n", + "297827.0257513064\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297605.6693262376\n", + "297603.0752248972\n", + "297846.2494446464\n", + "297838.9260958417\n", + "297747.8592294771\n", + "297748.88198636496\n", + "297629.281245547\n", + "297630.8831008526\n", + "297856.7208768194\n", + "297858.8065119703\n", + "297896.4972446103\n", + "297912.783650404\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297742.6222117954\n", + "297727.25004291494\n", + "297744.78000442253\n", + "297745.8241508577\n", + "297880.8074742805\n", + "297876.7954823588\n", + "297926.4463263305\n", + "297926.6802023382\n", + "297681.8627296707\n", + "297682.08032223984\n", + "297655.0598435738\n", + "297657.3602135141\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297938.4865989495\n", + "297938.9224343352\n", + "298044.2087798041\n", + "298033.189614837\n", + "297737.7939213607\n", + "297731.4239471909\n", + "297997.05197726307\n", + "297996.4869212306\n", + "297663.2985390386\n", + "297648.37186505616\n", + "297856.38563151145\n", + "297855.40351261187\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297758.9773723693\n", + "297756.42455969926\n", + "297846.99736443354\n", + "297862.2945462359\n", + "297976.2441732159\n", + "297975.4206463557\n", + "297767.8811980438\n", + "297761.13937168487\n", + "297740.0854176577\n", + "297742.14179957\n", + "297997.0244614666\n", + "297997.2801615055\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297741.6728326457\n", + "297753.1822861897\n", + "298025.44841289514\n", + "298025.52074443334\n", + "297926.9125022162\n", + "297926.27786823735\n", + "297922.19545892865\n", + "297923.086408062\n", + "297509.33971359715\n", + "297518.27650750143\n", + "297932.5308396082\n", + "297919.5302194291\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297918.6230855262\n", + "297920.1957777162\n", + "297723.29552125244\n", + "297724.31900438474\n", + "297689.15048093535\n", + "297689.5219380253\n", + "297991.3944703036\n", + "297991.46889638505\n", + "297793.03723426274\n", + "297795.58427010546\n", + "297751.0666136025\n", + "297736.20833673456\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298019.0277972613\n", + "298021.12387346645\n", + "297777.35042865266\n", + "297784.1701284144\n", + "297791.31665774406\n", + "297794.1559885281\n", + "297939.0570889442\n", + "297940.857674566\n", + "297821.95214271254\n", + "297821.09169971675\n", + "297708.69544422545\n", + "297709.0377058775\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297948.277167344\n", + "297964.81831034453\n", + "297927.4160553323\n", + "297927.58884882793\n", + "297808.63022222964\n", + "297824.9193871379\n", + "297877.0553244042\n", + "297881.02369011287\n", + "297789.84795302723\n", + "297809.9879732383\n", + "297988.7615320477\n", + "297991.77778013435\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298010.92249152344\n", + "297997.02069759293\n", + "297916.189151199\n", + "297915.2691555487\n", + "297846.92684360454\n", + "297847.11887417757\n", + "297941.2879903572\n", + "297940.75022492994\n", + "297980.575830853\n", + "297971.88662071375\n", + "297836.1932874885\n", + "297839.3121298605\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297809.4073398874\n", + "297804.2066730048\n", + "297749.7197309744\n", + "297743.63414034847\n", + "297747.69757296314\n", + "297746.8623023431\n", + "297900.1864516117\n", + "297888.68649952766\n", + "297803.83346923086\n", + "297809.76414976246\n", + "297815.11994464055\n", + "297813.57079927326\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297621.8769978312\n", + "297626.1980857876\n", + "297823.34160827356\n", + "297825.33099389053\n", + "298009.4808148424\n", + "298031.3543827531\n", + "297853.3813233664\n", + "297850.2507064974\n", + "297818.8451207914\n", + "297815.66571874265\n", + "297949.06159684045\n", + "297970.22193997283\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297750.87940879667\n", + "297753.34194110485\n", + "297525.9684320256\n", + "297526.34003482835\n", + "297886.8506694116\n", + "297872.9674739072\n", + "297859.502086549\n", + "297861.93878741143\n", + "297684.78371752857\n", + "297684.13290524157\n", + "297666.37402583245\n", + "297661.30825701845\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297962.6009249653\n", + "297960.9611649755\n", + "297699.54582383065\n", + "297700.89062127226\n", + "298029.44018360774\n", + "298030.6745097358\n", + "297810.5676451153\n", + "297809.8730917602\n", + "297908.5802932804\n", + "297908.66236983234\n", + "297725.9548232241\n", + "297735.8196723581\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297774.8062102864\n", + "297773.84392846737\n", + "297804.9269434263\n", + "297801.17216298345\n", + "297878.8018961518\n", + "297877.8280070966\n", + "297732.0037774117\n", + "297734.645593635\n", + "297991.5448923035\n", + "297991.935421105\n", + "297873.71419051604\n", + "297876.01747845777\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297784.3375746216\n", + "297786.69737651\n", + "297832.60709094873\n", + "297832.84004256665\n", + "297965.31000382215\n", + "297950.91613180086\n", + "297851.4341982288\n", + "297848.6988725662\n", + "297945.9892112674\n", + "297947.0129293307\n", + "297550.0391111617\n", + "297538.11155405914\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298008.85998826247\n", + "298021.02103539475\n", + "297749.61284586997\n", + "297749.82494635106\n", + "297752.9480948208\n", + "297756.09943382954\n", + "297774.6260966102\n", + "297761.4470042805\n", + "297955.3727817849\n", + "297959.7428639017\n", + "297761.20426796493\n", + "297761.4448266664\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297862.11875107064\n", + "297862.3480713468\n", + "297825.0473358818\n", + "297824.9473818802\n", + "297868.6302464183\n", + "297856.31064606365\n", + "297819.82236505166\n", + "297828.29841527273\n", + "297874.8365840081\n", + "297872.3363514772\n", + "297786.89790370007\n", + "297797.40024800657\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297862.98235440056\n", + "297858.7743329978\n", + "297738.311427637\n", + "297731.78929990804\n", + "297711.54875762097\n", + "297715.90047751955\n", + "297864.39914592047\n", + "297854.26278048404\n", + "297776.52819050255\n", + "297772.8897123971\n", + "297872.1538161229\n", + "297875.0648542643\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297892.5906718898\n", + "297892.6819639291\n", + "297835.26293608133\n", + "297837.2265037623\n", + "297838.555739991\n", + "297840.46982038877\n", + "297778.90679688845\n", + "297777.2800962659\n", + "297906.29147094354\n", + "297928.64777629735\n", + "297812.25915277965\n", + "297812.281075258\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297779.15533779404\n", + "297758.6645989346\n", + "297850.2400204638\n", + "297851.9411126675\n", + "297805.98943247576\n", + "297807.0589334977\n", + "297886.6469957138\n", + "297884.7563305668\n", + "297632.3162688816\n", + "297662.2540589157\n", + "297694.517320722\n", + "297695.2862299975\n", + "(22, 104)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297727.628048909\n", + "297727.6518519633\n", + "297761.97204848484\n", + "297776.9314651614\n", + "297947.32502482546\n", + "297935.0829251115\n", + "297860.4533167461\n", + "297863.18865669693\n", + "297549.4841603889\n", + "297531.9978134807\n", + "297745.6554639521\n", + "297755.69342303753\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297820.7683458737\n", + "297819.6696889504\n", + "297749.87607629504\n", + "297750.484635827\n", + "297822.74368756666\n", + "297824.17556014797\n", + "297791.62156333704\n", + "297791.6318419417\n", + "297839.7233419065\n", + "297842.22105417086\n", + "297948.08370774536\n", + "297949.5402105175\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297792.724637528\n", + "297792.824589368\n", + "297855.73457279796\n", + "297865.4088470151\n", + "297707.87109234295\n", + "297711.12848030514\n", + "297747.18705158116\n", + "297754.08261477883\n", + "297816.263270134\n", + "297817.3693670977\n", + "297863.0208471021\n", + "297859.45340074913\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297633.5159575085\n", + "297627.10633141967\n", + "297769.3270519756\n", + "297766.64698251215\n", + "297882.57833969156\n", + "297883.9855818141\n", + "297776.7215014909\n", + "297776.7505311626\n", + "297705.25699189847\n", + "297705.5113258659\n", + "297802.8541206307\n", + "297811.47801998036\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297798.1531624644\n", + "297803.1044022732\n", + "297713.61182559025\n", + "297697.7027123093\n", + "297823.7330615133\n", + "297825.26126925397\n", + "297926.4056979398\n", + "297927.7768873386\n", + "297770.4884059159\n", + "297772.6515398858\n", + "297625.905843861\n", + "297620.92306608363\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297893.00346459384\n", + "297889.2493707219\n", + "297781.7135085017\n", + "297797.17897541134\n", + "297991.6252117097\n", + "297995.528201208\n", + "297579.98739671626\n", + "297579.5490069672\n", + "297846.03558302374\n", + "297841.74821265147\n", + "297854.2641851355\n", + "297856.1917481439\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297664.6573066534\n", + "297665.6204008621\n", + "297939.4375814608\n", + "297962.9750560109\n", + "297748.7695659494\n", + "297748.79819554865\n", + "297788.2063970163\n", + "297789.1279576122\n", + "297846.6349019288\n", + "297843.5931464374\n", + "297866.1206051386\n", + "297863.4091786272\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297683.60253462236\n", + "297677.9759353993\n", + "297635.0463653587\n", + "297640.54828801396\n", + "297779.9118994026\n", + "297780.85687586485\n", + "297795.2352025845\n", + "297792.1148807289\n", + "297751.62186142115\n", + "297751.772711635\n", + "297869.8672841287\n", + "297868.81741102354\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297805.11139478744\n", + "297805.7183792677\n", + "297823.2193659055\n", + "297823.7489741238\n", + "297903.67533044884\n", + "297887.22741949843\n", + "297950.97147809947\n", + "297930.24262432306\n", + "297822.35358929995\n", + "297821.2708274334\n", + "297964.73063437815\n", + "297976.4740226726\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297734.4521169402\n", + "297736.0374276389\n", + "297940.65955261077\n", + "297942.940404819\n", + "297740.70564673265\n", + "297733.2960466131\n", + "297811.25382740883\n", + "297810.03889776475\n", + "297749.86370094796\n", + "297755.90863563126\n", + "297784.44892459613\n", + "297772.774826774\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297827.2621327616\n", + "297827.34062663786\n", + "297891.5058819028\n", + "297893.15602509916\n", + "297904.5226585774\n", + "297905.13905643095\n", + "297780.527704653\n", + "297773.5103608108\n", + "297953.6979212002\n", + "297952.49243152334\n", + "297796.0292421405\n", + "297796.2964133919\n", + "(22,)\n", + "empty in 0\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297847.9894252528\n", + "297850.5230787756\n", + "297936.2165163167\n", + "297936.33632663195\n", + "297749.9201915361\n", + "297742.65802114544\n", + "297829.5712146614\n", + "297840.19737339474\n", + "297811.16159860697\n", + "297820.1837513997\n", + "297897.4524198879\n", + "297891.9729344135\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297865.85763969104\n", + "297887.3886624263\n", + "297842.96835421544\n", + "297837.6234554089\n", + "297892.94771735795\n", + "297893.90326294047\n", + "297965.53564608924\n", + "297963.486898719\n", + "297856.8882917447\n", + "297858.63386027265\n", + "297879.7904674588\n", + "297879.79600530426\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297552.2305892868\n", + "297556.9629917907\n", + "297933.9211700937\n", + "297937.90590866166\n", + "297751.19792488986\n", + "297752.75620104955\n", + "297812.7807063594\n", + "297812.9725135595\n", + "297689.19274424657\n", + "297700.9720791559\n", + "297918.14128079015\n", + "297916.6688383369\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297771.7709281157\n", + "297759.6531568097\n", + "297640.9252271222\n", + "297660.51257352694\n", + "297924.16238270514\n", + "297912.00122417184\n", + "297749.5325294537\n", + "297732.38162651146\n", + "297658.2245166707\n", + "297680.0159317734\n", + "297847.02547771164\n", + "297849.66938983457\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297689.5170092403\n", + "297690.03748007974\n", + "297816.5391815383\n", + "297811.60306371114\n", + "297694.38969740685\n", + "297686.99089933955\n", + "297724.38981260604\n", + "297727.6984802823\n", + "297814.03166071227\n", + "297814.51637731714\n", + "297711.67509394744\n", + "297695.23552314704\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297713.72480313806\n", + "297714.3559725292\n", + "297907.8191763481\n", + "297906.8186480316\n", + "297869.60111262277\n", + "297853.44037462707\n", + "298012.52983652765\n", + "298034.9603247985\n", + "298111.8019982511\n", + "298110.6030695679\n", + "297891.1735552745\n", + "297891.97296141635\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297736.3822770764\n", + "297725.07074269454\n", + "297887.87139386026\n", + "297887.94649106706\n", + "297789.0377118593\n", + "297795.4071229691\n", + "298000.06175242865\n", + "298000.1921458393\n", + "297829.7948841451\n", + "297835.55131581257\n", + "297792.0850729527\n", + "297788.0969109043\n", + "(22,)\n", + "2257055\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297966.4582548242\n", + "297966.26465123816\n", + "297682.42490782693\n", + "297687.5196860424\n", + "297715.65541911504\n", + "297718.838565973\n", + "297835.15419884154\n", + "297829.99174362817\n", + "298032.06425931724\n", + "298033.06736845203\n", + "297875.07851354877\n", + "297890.58691713435\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297933.6492079999\n", + "297933.6788374318\n", + "297857.7475934947\n", + "297842.7967772905\n", + "297808.38960543124\n", + "297808.38198852766\n", + "297723.24450920004\n", + "297723.12871997745\n", + "297955.7841923659\n", + "297956.51129152946\n", + "297932.1301636033\n", + "297947.9641030758\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297821.7798675415\n", + "297821.1409235082\n", + "297907.16815835075\n", + "297905.3441142145\n", + "297985.5906397976\n", + "297988.7427758196\n", + "297723.93633480865\n", + "297719.531407468\n", + "297870.8178072094\n", + "297871.35460399353\n", + "297806.54331883555\n", + "297804.4815244792\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298001.3217336762\n", + "298003.1109252488\n", + "298020.5094112003\n", + "298016.02800330386\n", + "297643.2951735035\n", + "297645.3094376877\n", + "297946.28976078174\n", + "297934.26006537344\n", + "297792.2070767025\n", + "297780.6579715457\n", + "297811.87768729\n", + "297800.5672067943\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297911.0920148934\n", + "297907.7193896554\n", + "297829.7767951351\n", + "297830.50730647956\n", + "297628.18259125086\n", + "297627.4689443167\n", + "297596.4158083984\n", + "297592.62350957614\n", + "297666.1740790411\n", + "297663.6163181563\n", + "297785.66974122165\n", + "297781.8727595871\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297850.5940127578\n", + "297850.78838670853\n", + "297859.63745865814\n", + "297858.8576855458\n", + "297699.0867328405\n", + "297699.08676105103\n", + "297987.08497103734\n", + "297987.86133079784\n", + "297612.8129173416\n", + "297614.3749201836\n", + "297809.5672163709\n", + "297817.13787601463\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297840.76448129176\n", + "297840.8398004477\n", + "297733.0966839215\n", + "297753.1781187294\n", + "297964.4647618481\n", + "297969.1538904733\n", + "298036.6989353579\n", + "298038.44966092386\n", + "297852.4899311701\n", + "297859.02279570437\n", + "297834.5252935936\n", + "297832.1109225733\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297721.7850861805\n", + "297720.90963688935\n", + "297832.7203344701\n", + "297815.1695121872\n", + "297980.49761768203\n", + "297984.2107248972\n", + "297827.7174954647\n", + "297830.60082806944\n", + "297764.1111132522\n", + "297758.4368294868\n", + "297805.6479922426\n", + "297807.8653230871\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297806.0784006014\n", + "297807.9272269835\n", + "297921.2282146271\n", + "297918.5601674645\n", + "297575.78654333437\n", + "297569.3352213605\n", + "297831.19480321446\n", + "297827.21120401524\n", + "297699.5255237069\n", + "297689.67093036434\n", + "297695.33936186886\n", + "297695.3654775538\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297837.9092050366\n", + "297837.9073851813\n", + "297715.1456585999\n", + "297711.86383938877\n", + "297705.25794703735\n", + "297705.2585762992\n", + "297818.63807383284\n", + "297819.84810838435\n", + "297815.7036896098\n", + "297816.4903093666\n", + "297707.7751599474\n", + "297727.45469964435\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297912.36332004284\n", + "297925.96151713637\n", + "297818.33750708343\n", + "297818.3029508958\n", + "297670.87463758467\n", + "297673.0112141555\n", + "297526.1238999739\n", + "297521.30422841734\n", + "297725.7138588501\n", + "297725.85324265144\n", + "297781.51584721747\n", + "297782.1772599676\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297898.37958465493\n", + "297888.603166489\n", + "297768.875127248\n", + "297761.9486234303\n", + "297674.2318439055\n", + "297670.32761952886\n", + "297922.60125318146\n", + "297929.36290520855\n", + "297792.1598249019\n", + "297795.34813969146\n", + "297901.08655860386\n", + "297921.0381854839\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297956.9890146223\n", + "297958.3202002168\n", + "297928.8922046583\n", + "297928.89536031504\n", + "297908.63148452906\n", + "297906.49678821635\n", + "297828.26898592396\n", + "297830.6039368728\n", + "297787.7375704816\n", + "297786.97438949684\n", + "297918.31670714886\n", + "297920.6426871246\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297844.04655171116\n", + "297840.1658535168\n", + "297762.05804427364\n", + "297748.51331933285\n", + "297950.3872066136\n", + "297947.63269183075\n", + "297869.369518043\n", + "297869.3262929088\n", + "297883.23469165375\n", + "297890.0698714937\n", + "298010.109185686\n", + "298010.13445280073\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297800.3160492464\n", + "297800.6004466784\n", + "297952.273246749\n", + "297952.3921144908\n", + "298012.85992842924\n", + "298014.53605990554\n", + "298084.6975079244\n", + "298045.6296493129\n", + "297709.0506052647\n", + "297712.7996871476\n", + "297675.08578528906\n", + "297671.20366173744\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298046.7347771852\n", + "298042.64702033775\n", + "297735.47678765573\n", + "297738.6198824012\n", + "297784.878131965\n", + "297769.47532014083\n", + "297882.5534559112\n", + "297896.99529645895\n", + "297715.90224275045\n", + "297713.7287067263\n", + "297770.326949111\n", + "297771.7462666257\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297875.080472198\n", + "297877.0768465275\n", + "297822.3614113278\n", + "297809.1886418411\n", + "297826.0144094134\n", + "297826.46325576794\n", + "297624.5968124715\n", + "297632.7216966145\n", + "297737.7764258064\n", + "297737.9688497646\n", + "297927.8969663139\n", + "297915.1783608317\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297701.1319090772\n", + "297705.6886862765\n", + "297871.6495281487\n", + "297885.1152521979\n", + "297954.831293259\n", + "297955.912914611\n", + "297759.71774592774\n", + "297763.87936201354\n", + "297769.8319825814\n", + "297764.4971174679\n", + "297858.8820644943\n", + "297859.78716569557\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297728.5973351152\n", + "297730.3952150994\n", + "297884.23573815497\n", + "297883.9727845802\n", + "297684.0367390641\n", + "297688.9608993824\n", + "297904.23657064204\n", + "297911.19246824115\n", + "297784.78266254836\n", + "297806.33026386535\n", + "297798.9318531742\n", + "297799.1908757709\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297869.8773080485\n", + "297860.36098701274\n", + "297882.5121018081\n", + "297879.3853693409\n", + "297863.14129704627\n", + "297861.7843718365\n", + "297643.537803683\n", + "297647.09763753135\n", + "297668.30915536184\n", + "297673.04655688046\n", + "297790.1607200429\n", + "297793.24887646816\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297833.85576435033\n", + "297837.68220664054\n", + "297846.41997305263\n", + "297846.48362810176\n", + "297827.5159738212\n", + "297845.3102529416\n", + "297925.98224958143\n", + "297925.9576197189\n", + "297931.140548214\n", + "297931.366417277\n", + "297750.85549578274\n", + "297754.9742279307\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297719.27507816174\n", + "297730.7791535591\n", + "297866.9246159508\n", + "297861.0431142685\n", + "297836.39818156936\n", + "297848.7105234155\n", + "297803.3211836446\n", + "297803.4769152924\n", + "297838.9519814447\n", + "297838.8511185038\n", + "297775.03732919786\n", + "297790.8300604142\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297663.80330072675\n", + "297656.74088832823\n", + "297861.3466664261\n", + "297855.0312639412\n", + "297898.32801717066\n", + "297898.92717360717\n", + "297624.3234246253\n", + "297638.8611164775\n", + "297921.7997098286\n", + "297922.04537800705\n", + "297651.05631322105\n", + "297648.56382053986\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297913.2203700353\n", + "297912.90506197023\n", + "297657.2488800221\n", + "297656.213638237\n", + "297811.6086020174\n", + "297828.7727673793\n", + "297792.64051595796\n", + "297811.0415134578\n", + "297900.14603097376\n", + "297895.0858224091\n", + "298077.7680468505\n", + "298066.69089714263\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297744.6218878714\n", + "297756.8219795029\n", + "297620.3939322075\n", + "297625.84732389153\n", + "297708.5318478252\n", + "297708.5524877735\n", + "297944.2218920187\n", + "297948.3695590242\n", + "297846.53032273636\n", + "297847.0455129391\n", + "297904.4657868706\n", + "297905.1183256595\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297595.7337150823\n", + "297596.4319078969\n", + "297938.49320461665\n", + "297943.00689879927\n", + "297932.24992375105\n", + "297932.909976574\n", + "297870.3599508076\n", + "297869.3511493194\n", + "297781.7285436531\n", + "297781.9610867033\n", + "297801.02733526856\n", + "297803.2310925233\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297744.0195108333\n", + "297755.15771213075\n", + "297843.2344183582\n", + "297843.5797253047\n", + "297722.75652651634\n", + "297720.5048258652\n", + "297751.46550187835\n", + "297761.78634196875\n", + "297934.2310177086\n", + "297920.0227479146\n", + "297775.46954988095\n", + "297775.4941248208\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297888.1430303194\n", + "297887.9596830592\n", + "297812.28006660694\n", + "297811.8435470615\n", + "297719.7689917138\n", + "297742.3921008491\n", + "297674.897851286\n", + "297671.9019553971\n", + "297852.90264742397\n", + "297857.27306875994\n", + "297934.6486196682\n", + "297934.8490896465\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297684.6446909004\n", + "297699.3558021322\n", + "297682.9984365098\n", + "297693.38351830514\n", + "297729.20992537274\n", + "297728.4419324205\n", + "297807.07107245683\n", + "297807.0847793963\n", + "297660.5760957607\n", + "297662.98697756906\n", + "297953.7995709095\n", + "297933.9921051405\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297790.76310494804\n", + "297788.93215129233\n", + "297765.81201861484\n", + "297740.07787489163\n", + "297890.47022947494\n", + "297890.6337304529\n", + "297941.9422902112\n", + "297941.94260111736\n", + "297645.4343266415\n", + "297645.4867834694\n", + "297838.6076907179\n", + "297855.6689117697\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297788.4797839702\n", + "297785.2816583131\n", + "297744.284938599\n", + "297744.08272286755\n", + "297675.5476980295\n", + "297671.8170061984\n", + "297664.70673411986\n", + "297665.16669306025\n", + "298010.4461603151\n", + "298010.29462801846\n", + "297648.3291816169\n", + "297648.3602721525\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297869.70754666836\n", + "297856.70508560666\n", + "297701.2792308258\n", + "297701.07690116524\n", + "297893.2320030163\n", + "297891.31446782267\n", + "297550.29445624165\n", + "297557.2988506319\n", + "297853.540989927\n", + "297855.36095790105\n", + "297657.2945078585\n", + "297658.4564525968\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297887.1639664306\n", + "297887.38947537425\n", + "297851.3467956696\n", + "297851.23025183234\n", + "297792.26213113137\n", + "297789.07688811125\n", + "297809.4371337374\n", + "297811.6163705165\n", + "297664.4973556748\n", + "297665.3553474185\n", + "297762.7744405159\n", + "297764.0641427691\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297805.8432266456\n", + "297800.9595934734\n", + "297957.70500142453\n", + "297957.88921436155\n", + "297864.94745123334\n", + "297863.6203527265\n", + "297819.5738274411\n", + "297821.2514958685\n", + "297740.1607537432\n", + "297726.44079588115\n", + "297643.23503469594\n", + "297657.5704810912\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298002.3115615681\n", + "298003.10979855235\n", + "297667.500736403\n", + "297688.18628311245\n", + "297920.06890581956\n", + "297916.330748792\n", + "297955.8893384996\n", + "297941.0125869136\n", + "297948.4221185879\n", + "297949.4999878023\n", + "297800.2862577313\n", + "297799.5222556767\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297653.8050443361\n", + "297655.32758573396\n", + "297957.2810357677\n", + "297952.98570115434\n", + "297852.1580919603\n", + "297852.51220256434\n", + "298073.59147137235\n", + "298059.25654816086\n", + "297750.11870813306\n", + "297759.6964189376\n", + "297669.4623647742\n", + "297669.59586021776\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297604.007349109\n", + "297606.41963252\n", + "298112.28641410125\n", + "298112.2776048768\n", + "297849.87763381394\n", + "297853.0575229029\n", + "297966.74529741105\n", + "297971.9136749868\n", + "297781.6688541553\n", + "297794.60325116344\n", + "297889.62610021356\n", + "297881.2262689817\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297919.99790962244\n", + "297907.9685321557\n", + "297808.5485130797\n", + "297808.88729400025\n", + "298100.97897860396\n", + "298102.1915258077\n", + "297818.38017798867\n", + "297821.1328383381\n", + "297811.47013441357\n", + "297828.3091891642\n", + "297838.7623064029\n", + "297841.7700031027\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297773.72385235375\n", + "297780.26367358613\n", + "297840.58521039854\n", + "297840.5763144381\n", + "297787.38486748456\n", + "297787.4876023128\n", + "297570.9794565486\n", + "297560.4415497164\n", + "298004.3358161462\n", + "297998.8740533108\n", + "297889.0216040876\n", + "297891.23120739067\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297761.4976335805\n", + "297746.60936194856\n", + "297737.7504407194\n", + "297755.4722953299\n", + "297787.53351370385\n", + "297788.5468403573\n", + "297872.85254557035\n", + "297871.5897809099\n", + "297910.4091762525\n", + "297899.1737270278\n", + "297705.73608552094\n", + "297705.9626895116\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297791.50527903985\n", + "297792.36151822883\n", + "297523.5113682394\n", + "297524.18433598697\n", + "297959.0601723861\n", + "297959.1775230034\n", + "297788.2548917959\n", + "297785.8020079625\n", + "297789.95657799504\n", + "297796.1409745457\n", + "297866.3659452594\n", + "297852.1152435997\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297794.4884045358\n", + "297794.62598853064\n", + "297781.65637835406\n", + "297777.8365587512\n", + "297660.31007467024\n", + "297652.76441265707\n", + "297754.98217003606\n", + "297754.32756874966\n", + "297749.2076501114\n", + "297749.29883230804\n", + "297740.7055989351\n", + "297740.7773053808\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297833.17506012757\n", + "297834.0885361942\n", + "298110.1747974456\n", + "298110.4280197782\n", + "297832.39683075616\n", + "297831.7011903431\n", + "297859.5014360763\n", + "297858.21325750265\n", + "297766.8501768026\n", + "297769.8336700343\n", + "297774.6477082089\n", + "297776.12938280596\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297955.95610975294\n", + "297955.1557416258\n", + "297870.5060445121\n", + "297868.6410025249\n", + "297967.53883854474\n", + "297970.78540974355\n", + "297928.33769831347\n", + "297934.14223881665\n", + "297760.78829113266\n", + "297760.63418144913\n", + "297480.13906053355\n", + "297478.1735265613\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297772.4494915364\n", + "297761.42244888685\n", + "297880.7279775246\n", + "297884.02504933794\n", + "297846.27898334747\n", + "297841.88854947407\n", + "297884.05751862325\n", + "297901.8884632786\n", + "297695.9768312957\n", + "297726.74858426995\n", + "297684.10109262855\n", + "297684.16438439855\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297633.0346630785\n", + "297635.78452953964\n", + "297887.1348838995\n", + "297887.5382392514\n", + "297829.91556767374\n", + "297818.42155901436\n", + "297741.7713353871\n", + "297725.5089642363\n", + "297781.27258471446\n", + "297777.8359520985\n", + "297546.2519084545\n", + "297545.1673887667\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297775.9671644047\n", + "297751.6049252155\n", + "297650.39881271863\n", + "297640.9805756867\n", + "297912.42689740466\n", + "297910.54200197046\n", + "297729.47160530696\n", + "297735.226261924\n", + "297633.92765997007\n", + "297623.57518808247\n", + "297667.5288082917\n", + "297666.5757756521\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297756.9058200166\n", + "297746.9589047148\n", + "297874.30780043994\n", + "297877.6901957846\n", + "297953.9887723875\n", + "297957.36069156445\n", + "297949.6098208227\n", + "297949.09692958527\n", + "297890.7640779943\n", + "297893.9943549579\n", + "297614.767034728\n", + "297620.660014687\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297812.8022764363\n", + "297811.48292527563\n", + "297682.4221529795\n", + "297681.1526782471\n", + "297790.80607741524\n", + "297791.289491482\n", + "298023.89117538865\n", + "298023.6552594901\n", + "297773.95459879487\n", + "297773.40847136034\n", + "297758.9647710636\n", + "297760.1004792085\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297888.856242844\n", + "297893.8506881836\n", + "297883.13207596255\n", + "297883.28494103387\n", + "297909.2407638241\n", + "297908.12471081066\n", + "297910.0810644968\n", + "297892.4817259791\n", + "297819.5852198628\n", + "297821.3663326042\n", + "297836.687349077\n", + "297854.0413080416\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297963.3933396501\n", + "297963.867334396\n", + "297743.44133825187\n", + "297738.8031002802\n", + "297710.9547447473\n", + "297712.02146948955\n", + "297893.6332276975\n", + "297893.5841088467\n", + "297891.6973401593\n", + "297893.06609543937\n", + "298070.1536813467\n", + "298072.20697369776\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297733.77722873085\n", + "297729.61954810837\n", + "297781.8090702023\n", + "297781.36509484553\n", + "297757.3418320118\n", + "297757.738811726\n", + "297899.39703302766\n", + "297904.39631840476\n", + "297845.9739464491\n", + "297833.92036698497\n", + "297925.54598045297\n", + "297925.2366374247\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297870.27145279857\n", + "297881.7830465144\n", + "297725.2845034844\n", + "297725.7290375254\n", + "297840.74754838506\n", + "297835.03861420276\n", + "297659.2138191122\n", + "297667.4305984825\n", + "297831.7241404724\n", + "297832.8907390014\n", + "298099.8284421189\n", + "298093.9128965955\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298055.86390337226\n", + "298071.05966611305\n", + "297693.6323718052\n", + "297693.7814477213\n", + "297815.675180404\n", + "297811.0043522314\n", + "297947.0757324636\n", + "297948.56495544803\n", + "297834.692442468\n", + "297834.4530615308\n", + "297658.3127424081\n", + "297670.86100313487\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297711.5677305872\n", + "297712.0348328709\n", + "297721.5374637404\n", + "297720.3177438253\n", + "297698.5002605693\n", + "297680.9864078524\n", + "297940.7855557351\n", + "297938.42215959256\n", + "297743.28862477903\n", + "297729.2340674707\n", + "298022.4170890655\n", + "298023.30142245616\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297673.1108516551\n", + "297673.1635680656\n", + "297757.81865566055\n", + "297758.5806653685\n", + "297753.237959005\n", + "297754.2219002776\n", + "297846.07877574407\n", + "297847.66279337934\n", + "297871.8836241556\n", + "297883.16502834536\n", + "297744.17962995876\n", + "297744.1796724586\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297690.00898871064\n", + "297688.76996698347\n", + "297932.14310213644\n", + "297933.26233184326\n", + "297891.58311986213\n", + "297895.95755206415\n", + "297813.5643242589\n", + "297815.96897349885\n", + "297929.45678187796\n", + "297929.785828148\n", + "297767.6401290265\n", + "297768.35550221\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298067.1833543539\n", + "298068.1916899533\n", + "297889.2789417763\n", + "297891.5400796811\n", + "297635.2156962775\n", + "297638.8808337406\n", + "297918.3612840761\n", + "297914.473136692\n", + "297841.48973503546\n", + "297861.2645953061\n", + "297800.45021043357\n", + "297799.1722556382\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297622.90372796333\n", + "297619.5108510369\n", + "297878.6693461193\n", + "297878.15741804003\n", + "297913.5836918722\n", + "297914.40630576044\n", + "297897.8696178922\n", + "297899.08571277716\n", + "297977.9109509813\n", + "297979.4045641232\n", + "297918.0063630704\n", + "297917.8666666073\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297892.01482162124\n", + "297899.6982815164\n", + "297957.79805408657\n", + "297951.5050407796\n", + "297932.69087804056\n", + "297937.43069119455\n", + "297977.83378451446\n", + "297977.83683613874\n", + "297766.77806615096\n", + "297765.90974356106\n", + "298024.0526249399\n", + "298025.4726433252\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297675.52142244345\n", + "297674.1938169222\n", + "297742.22963808785\n", + "297745.29954126204\n", + "297856.2691658224\n", + "297854.374976029\n", + "297743.3820239694\n", + "297752.29744745244\n", + "297861.9695149063\n", + "297860.48999717203\n", + "297821.9886583936\n", + "297840.7963908121\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297828.6983736167\n", + "297830.21743727656\n", + "298001.13131902675\n", + "298001.1690661373\n", + "298120.0221364705\n", + "298097.4557453707\n", + "297754.32979037834\n", + "297762.95267752244\n", + "298007.52060868003\n", + "298005.0451244878\n", + "297651.6859536037\n", + "297648.80913674954\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297688.30560501106\n", + "297688.92588481633\n", + "297585.75273284107\n", + "297608.18329798477\n", + "297794.8998121183\n", + "297792.4935156093\n", + "297668.0545510658\n", + "297670.507119221\n", + "297769.2854354945\n", + "297785.0026504179\n", + "297677.8376320855\n", + "297677.80286809156\n", + "(22,)\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297870.6715343171\n", + "297872.03839398193\n", + "297741.35425928683\n", + "297757.4902178872\n", + "297922.7332877733\n", + "297927.13440698344\n", + "298123.9083334732\n", + "298124.10214938974\n", + "297866.9110202544\n", + "297867.2227948843\n", + "297691.47792130103\n", + "297679.7674342032\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297909.6675959242\n", + "297913.8895811989\n", + "297709.2148731555\n", + "297713.05512340297\n", + "297702.37224238896\n", + "297714.2535212074\n", + "297705.93624944845\n", + "297695.84974120086\n", + "298076.80551239656\n", + "298073.6124974915\n", + "297893.1410765442\n", + "297893.43301727803\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297913.2319702698\n", + "297897.6642936157\n", + "298077.45268976816\n", + "298078.67150537926\n", + "298002.0421087936\n", + "297998.034588878\n", + "297804.07941487944\n", + "297805.72151023464\n", + "297697.11903944676\n", + "297699.92409975687\n", + "297866.48345915385\n", + "297863.39091111044\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297941.73795290187\n", + "297947.3205960282\n", + "297930.15453956433\n", + "297932.34618966654\n", + "297539.770940208\n", + "297540.4132680969\n", + "297863.2919467794\n", + "297863.793634678\n", + "298151.80478623987\n", + "298151.3311399816\n", + "297921.12502087385\n", + "297942.5653694084\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297877.0512532264\n", + "297876.7177706733\n", + "297702.5338575115\n", + "297698.8973524494\n", + "298001.3580205542\n", + "298000.568924803\n", + "297845.7442115105\n", + "297850.38272715884\n", + "297847.5814784937\n", + "297835.1632999587\n", + "297927.36201277474\n", + "297945.38460885553\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297754.0847658294\n", + "297757.8682221409\n", + "297747.5684600906\n", + "297746.0446984511\n", + "297868.1348220649\n", + "297863.7913809289\n", + "297536.8648107802\n", + "297537.43730179704\n", + "297899.15213200054\n", + "297898.79729897255\n", + "297838.19886503444\n", + "297846.3524817689\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297887.6868651001\n", + "297891.537951566\n", + "297892.0321279304\n", + "297890.8232630434\n", + "297803.65405224985\n", + "297802.00164381234\n", + "297777.28714779665\n", + "297780.9884280458\n", + "297745.76865076425\n", + "297742.8764091354\n", + "297814.8456668651\n", + "297809.1399404921\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297794.7362734615\n", + "297793.8327562429\n", + "297995.40901796595\n", + "297989.9596818257\n", + "297794.30711268797\n", + "297794.7698217225\n", + "297706.4815059891\n", + "297700.64667920093\n", + "297778.4955117373\n", + "297777.7825859512\n", + "297923.5553567514\n", + "297923.83224272745\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297827.8337205254\n", + "297827.7853204332\n", + "298025.45069823187\n", + "298027.5511178949\n", + "297825.091189094\n", + "297820.96950299945\n", + "297746.02127790166\n", + "297749.7947324744\n", + "297892.13783930324\n", + "297893.78525748046\n", + "297947.6206142516\n", + "297947.2553105909\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297876.21578031755\n", + "297875.1711868076\n", + "297696.7008187641\n", + "297696.8211122514\n", + "297910.93551252416\n", + "297903.99337089097\n", + "297821.78160214477\n", + "297824.88675903593\n", + "297896.03135660273\n", + "297896.26430767885\n", + "297876.28805902536\n", + "297877.60955842125\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297811.04890110967\n", + "297797.3432169456\n", + "297958.09607966465\n", + "297949.0467787489\n", + "297823.1716906224\n", + "297825.46090201504\n", + "297987.41422775283\n", + "297971.2410219093\n", + "297603.29622530227\n", + "297603.39582748606\n", + "298078.72075186647\n", + "298063.10280403384\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297838.29854284\n", + "297839.0904307609\n", + "297693.630110097\n", + "297693.7234094583\n", + "297544.97024735564\n", + "297547.1511599532\n", + "297596.3190979679\n", + "297589.41994534474\n", + "297813.937825802\n", + "297815.3074580015\n", + "297784.65035181737\n", + "297783.731273614\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297726.7506471785\n", + "297726.118038281\n", + "297826.06315647607\n", + "297826.08077726985\n", + "297970.0968823537\n", + "297970.51992793096\n", + "297919.05689116166\n", + "297913.473335764\n", + "297852.08140070346\n", + "297867.3256599985\n", + "297722.35746361857\n", + "297712.32526947884\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297790.085413029\n", + "297790.0374641785\n", + "297770.9058149478\n", + "297772.3113970316\n", + "297777.30705359275\n", + "297784.8924696056\n", + "297534.3439301903\n", + "297536.4947667666\n", + "297786.1497280262\n", + "297787.2313133012\n", + "298063.9372229394\n", + "298064.2540084686\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297830.59643575695\n", + "297817.3732374951\n", + "297779.5107820844\n", + "297772.56857033365\n", + "297738.54246049724\n", + "297740.0235568044\n", + "297912.0245061611\n", + "297913.6956135466\n", + "297856.7766477592\n", + "297842.6434603001\n", + "297847.19111844496\n", + "297842.6975562991\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297943.8169061744\n", + "297956.5589164099\n", + "297770.26552477287\n", + "297784.4735101359\n", + "297909.74918101623\n", + "297909.79727058206\n", + "297741.7175018311\n", + "297738.1711539953\n", + "297881.41280871537\n", + "297873.364812704\n", + "297929.73154648783\n", + "297949.5327806876\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "297753.5924309719\n", + "297738.19914333423\n", + "297823.7147979026\n", + "297812.9676161111\n", + "298190.7774736168\n", + "298191.95876531117\n", + "297751.8554854996\n", + "297751.857259167\n", + "297861.51710084477\n", + "297860.2499366431\n", + "297603.48083119583\n", + "297603.50445681025\n", + "(22,)\n", + "empty in 0\n", + "empty in 1\n", + "empty in 2\n", + "empty in 3\n", + "empty in 4\n", + "empty in 5\n", + "empty in 6\n", + "empty in 7\n", + "empty in 8\n", + "empty in 9\n", + "298003.6674688677\n", + "298019.22136549535\n", + "297874.26962104754\n", + "297883.3994579825\n", + "297894.585035921\n", + "297895.7353458587\n", + "297941.73187370884\n", + "297937.8947829755\n", + "297822.04546089843\n", + "297824.9457846594\n", + "297917.6620607952\n", + "297911.0571866818\n", + "(22,)\n", + "297645.60610390553\n", + "297645.6383833539\n", + "297782.3685428595\n", + "297769.5784300952\n", + "297664.0343085918\n", + "297642.96130852425\n", + "297673.6390255499\n", + "297673.22890094196\n", + "297561.00471605035\n", + "297562.0059042794\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297726.55565486045\n", + "297720.0232329921\n", + "298112.93920498464\n", + "298128.555932742\n", + "297844.90069655614\n", + "297835.54133316444\n", + "297925.72101690696\n", + "297916.9885110949\n", + "297843.27586006385\n", + "297844.374601051\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297834.92915309645\n", + "297830.5861696997\n", + "297843.5214073022\n", + "297842.5461227426\n", + "297882.13089262706\n", + "297868.6366113796\n", + "297624.9478162196\n", + "297625.78995939554\n", + "297915.13943225116\n", + "297917.1234843691\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298035.6386834222\n", + "298036.4795327568\n", + "297689.3216259138\n", + "297690.1775130095\n", + "297922.7710294518\n", + "297926.9721760482\n", + "297982.3600038109\n", + "297993.3740863475\n", + "297832.1084320012\n", + "297914.42772030254\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298037.9128438711\n", + "298038.41400069534\n", + "297597.4546575998\n", + "297597.53822008637\n", + "297917.6899149055\n", + "297935.0565011615\n", + "297767.4547633092\n", + "297766.3701435497\n", + "298006.1561522228\n", + "298004.6614621642\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297940.42450157035\n", + "297923.411212742\n", + "297876.7346707647\n", + "297878.41268526687\n", + "297940.2021021428\n", + "297930.78890210734\n", + "297867.1219378822\n", + "297881.31911699683\n", + "297936.83341052\n", + "297936.5333924762\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297745.74223160674\n", + "297764.2529805756\n", + "297738.1639519527\n", + "297736.3852309121\n", + "297878.2015394806\n", + "297867.53171649686\n", + "297874.2873149973\n", + "297889.10193758155\n", + "297875.8434105952\n", + "297891.48787520616\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297718.33296364086\n", + "297714.7153201021\n", + "297850.7616196392\n", + "297851.534190975\n", + "297755.7226297693\n", + "297753.4763146233\n", + "297736.928978454\n", + "297738.3895580577\n", + "297631.7790843039\n", + "297632.49994563084\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297832.19484811655\n", + "297821.06133702496\n", + "297929.1462178505\n", + "297933.61683562526\n", + "297665.4905209003\n", + "297664.8903218438\n", + "298004.99974645505\n", + "298005.4248405763\n", + "297931.34577664454\n", + "297931.7084333559\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297723.3913663904\n", + "297720.869654059\n", + "297928.75041528203\n", + "297925.9530882672\n", + "298016.620674056\n", + "298018.2067465073\n", + "297756.516144625\n", + "297752.31859313097\n", + "297903.66694760404\n", + "297904.40767998906\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297828.9640977852\n", + "297821.99053711904\n", + "297680.96108889114\n", + "297681.20762035326\n", + "297793.02546820143\n", + "297794.5557232505\n", + "297823.34329820477\n", + "297823.52524726186\n", + "297840.6634361704\n", + "297839.52960393304\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297876.1960671287\n", + "297861.2663196236\n", + "297856.81210025575\n", + "297855.12735502643\n", + "297747.6877878629\n", + "297747.6894506307\n", + "297804.6281183236\n", + "297807.79051681375\n", + "297864.81037685607\n", + "297845.5609924012\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297983.8978476588\n", + "297961.1176600575\n", + "297702.0878296169\n", + "297701.58478610654\n", + "297764.66198125825\n", + "297771.45468738506\n", + "297707.431271098\n", + "297711.7937905463\n", + "297796.3477439735\n", + "297797.84339340334\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297670.65378207027\n", + "297672.0521584816\n", + "297622.8374435982\n", + "297623.5280903264\n", + "297822.14613154234\n", + "297822.1549115131\n", + "297870.9706313681\n", + "297864.638846641\n", + "297794.2095641335\n", + "297792.66322106845\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297866.00045396626\n", + "297866.6398109613\n", + "297913.53098264855\n", + "297914.7843660366\n", + "297781.50894985406\n", + "297777.52062862285\n", + "297853.2319956156\n", + "297853.419217019\n", + "297820.8357688061\n", + "297821.28784857225\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297563.43299306417\n", + "297560.8438978093\n", + "297983.0220711902\n", + "297983.49903660023\n", + "297822.8051678857\n", + "297817.05604093696\n", + "297752.26382906147\n", + "297752.31216875964\n", + "297879.78045058943\n", + "297862.64692232356\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297886.86655035237\n", + "297891.5062640611\n", + "297904.6179029164\n", + "297898.0365341997\n", + "297764.5689781026\n", + "297773.2527213732\n", + "297939.83496533526\n", + "297942.5761357327\n", + "297721.158472031\n", + "297721.3307687598\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297507.7942349822\n", + "297507.943444652\n", + "297796.64111836214\n", + "297792.72867877485\n", + "297790.73988473846\n", + "297788.7348314558\n", + "297813.77736278187\n", + "297815.59687926143\n", + "297856.3935021367\n", + "297841.3452618402\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297832.1483310635\n", + "297846.14071084646\n", + "297868.8337327941\n", + "297868.8193466231\n", + "297751.44152746955\n", + "297751.66468946036\n", + "297957.81554993545\n", + "297957.6682959899\n", + "297609.6481261951\n", + "297619.3423064203\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297855.91313185106\n", + "297859.2176737406\n", + "297795.1687884461\n", + "297795.60515053885\n", + "297800.7064462862\n", + "297800.7656415121\n", + "297714.619060214\n", + "297710.63554704393\n", + "297729.72766437684\n", + "297732.8156646425\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297607.29149232653\n", + "297607.5766522143\n", + "297700.29877198575\n", + "297702.0804340606\n", + "297795.2743900263\n", + "297812.06852583966\n", + "297755.2378357625\n", + "297755.17818398913\n", + "297764.9750964002\n", + "297764.9740771205\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297966.6494835282\n", + "297968.7518577967\n", + "297771.84497284924\n", + "297760.457563636\n", + "297840.21485272126\n", + "297847.4512569859\n", + "298012.28181898914\n", + "298013.320341929\n", + "297712.65267184237\n", + "297727.240626219\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297854.718223641\n", + "297854.92396113934\n", + "297722.0080745041\n", + "297738.73243827315\n", + "297937.78160502133\n", + "297929.4826552029\n", + "297723.5919607271\n", + "297725.8185726013\n", + "297476.6477372674\n", + "297480.5535328099\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297464.22839902947\n", + "297464.3795640596\n", + "297925.4292281536\n", + "297933.52319303347\n", + "297877.12474195776\n", + "297860.78603059176\n", + "297896.02397267567\n", + "297892.3385298894\n", + "297730.28710316034\n", + "297729.9231643862\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297926.5221643544\n", + "297930.9485902958\n", + "297642.4032212533\n", + "297642.9665741141\n", + "297751.711107855\n", + "297758.37302414974\n", + "297590.1880475686\n", + "297592.9642608132\n", + "297922.5604678157\n", + "297910.01026164147\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297995.5902617477\n", + "297995.5905729327\n", + "297909.08891964616\n", + "297931.39855736704\n", + "297668.92821112345\n", + "297673.74339776096\n", + "297992.71785433317\n", + "297999.19596698496\n", + "297840.69332728826\n", + "297824.65575493575\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297939.4635761128\n", + "297939.52781293937\n", + "297678.9925302362\n", + "297680.1998471251\n", + "297838.6952112546\n", + "297843.6560226467\n", + "297592.47294234263\n", + "297592.98605361255\n", + "297760.73851971177\n", + "297757.8195897205\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297800.2457259028\n", + "297802.3206328503\n", + "297864.9321162556\n", + "297865.90303760784\n", + "297671.8297966806\n", + "297687.7170445834\n", + "298053.7856906306\n", + "298057.46577029844\n", + "297710.9676251238\n", + "297711.7853922082\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297939.9860891338\n", + "297949.3000785893\n", + "297746.530989475\n", + "297746.5702970653\n", + "297908.8546721421\n", + "297909.72571196355\n", + "297807.5670723442\n", + "297807.40700786264\n", + "297826.7931080204\n", + "297822.959507544\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297636.6781078484\n", + "297648.7911416667\n", + "297901.72420444037\n", + "297905.3674926944\n", + "297810.3903112116\n", + "297812.84182707244\n", + "297880.65715823905\n", + "297880.5349913406\n", + "297672.1351469533\n", + "297672.2631150705\n", + "empty in 10\n", + "empty in 11\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297779.60462823714\n", + "297802.2677380444\n", + "297877.80100434716\n", + "297903.4569355515\n", + "297794.1358143497\n", + "297793.6036566446\n", + "297542.6018587957\n", + "297560.47731385496\n", + "297955.91675535333\n", + "297955.94422675\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297690.0424878017\n", + "297690.55116167385\n", + "297840.05222767306\n", + "297839.60728644265\n", + "297774.52155708295\n", + "297779.5540330763\n", + "298034.81446511456\n", + "298033.8746372133\n", + "297898.9866740699\n", + "297893.93244238745\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297927.70602321706\n", + "297933.0864232101\n", + "298052.6970850391\n", + "298053.6629122245\n", + "297723.98607258033\n", + "297722.9192675909\n", + "297762.2389150045\n", + "297765.35341720015\n", + "297997.3219897384\n", + "297998.19560834335\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297743.30598878505\n", + "297757.7496179549\n", + "297789.5068660723\n", + "297803.243697659\n", + "298072.39610625367\n", + "298072.34058205236\n", + "297802.6812624997\n", + "297805.80571153644\n", + "297663.78148160386\n", + "297651.57684893307\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297717.1418248636\n", + "297717.2186567088\n", + "297725.0533416808\n", + "297725.64264173625\n", + "297942.9963164968\n", + "297944.2656467457\n", + "297782.047027077\n", + "297786.92916941736\n", + "297908.81343608286\n", + "297901.6102685777\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297661.5530266438\n", + "297667.59871566086\n", + "297844.09549369017\n", + "297857.37059800077\n", + "297886.5911746707\n", + "297886.37572186533\n", + "297759.3176479341\n", + "297759.2393586198\n", + "297779.00632251374\n", + "297780.1856882419\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297695.27102854085\n", + "297695.10913770273\n", + "297568.85827893554\n", + "297551.83474977606\n", + "297663.0326743397\n", + "297660.9431157385\n", + "297903.4170121067\n", + "297902.6024478386\n", + "297804.06963352585\n", + "297803.8743019806\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297823.3734846356\n", + "297823.62374506897\n", + "297929.7764975722\n", + "297935.1807343139\n", + "297804.6204934551\n", + "297829.2618112414\n", + "297879.2119397851\n", + "297881.1622527812\n", + "298076.0842197346\n", + "298063.30983408913\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298077.39772525826\n", + "298082.2219851525\n", + "297836.5569103733\n", + "297836.7213787764\n", + "297844.09234402486\n", + "297837.1480348082\n", + "297684.75878065213\n", + "297684.7676919817\n", + "297919.1697434123\n", + "297914.612349637\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297729.4018146251\n", + "297728.6473211185\n", + "297821.8290887548\n", + "297821.7367143531\n", + "297824.3646456757\n", + "297814.72182228643\n", + "297822.2341915142\n", + "297821.5003671944\n", + "297739.75590391585\n", + "297742.84794649476\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297724.6119061136\n", + "297744.4448753461\n", + "297863.83413820056\n", + "297864.772781071\n", + "297895.1982841839\n", + "297895.82988338603\n", + "297881.75680252933\n", + "297883.2584251321\n", + "297825.15694421966\n", + "297825.39129471785\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297998.2776422798\n", + "298000.3677577546\n", + "297987.7880182532\n", + "297989.2244215137\n", + "297775.9317333117\n", + "297782.64759743836\n", + "297868.4147880359\n", + "297869.31017460884\n", + "297849.35791625583\n", + "297849.79197786585\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297942.496502132\n", + "297945.7369012959\n", + "297835.9347223595\n", + "297845.5567236995\n", + "297835.8218583121\n", + "297836.83827411773\n", + "297832.0951705299\n", + "297833.04079368134\n", + "297830.22383670125\n", + "297830.4547831643\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297772.9222883789\n", + "297771.6040894608\n", + "297632.4010511521\n", + "297630.2491631872\n", + "297848.9478583817\n", + "297875.4969119827\n", + "297792.48475563055\n", + "297782.68589468783\n", + "297747.3851338001\n", + "297750.13743371144\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297876.9877490876\n", + "297877.40825015685\n", + "297714.74916859757\n", + "297708.0182091783\n", + "297739.6555992967\n", + "297740.24900452106\n", + "297773.63144838857\n", + "297777.64233131876\n", + "297692.02362906496\n", + "297692.37732924393\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297990.9566183721\n", + "297991.8233854959\n", + "297736.9151300685\n", + "297743.7058050931\n", + "297983.06019325595\n", + "297962.24497041776\n", + "297817.34196013823\n", + "297813.63770134834\n", + "297855.9866556824\n", + "297843.7579339643\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297953.3278770136\n", + "297951.90262565046\n", + "297801.0562869607\n", + "297801.1409114065\n", + "297677.74583553866\n", + "297678.9624204412\n", + "297721.90709223936\n", + "297720.72723509604\n", + "297803.90250802453\n", + "297803.8507993931\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297640.2785072186\n", + "297639.4402322269\n", + "297865.41004066425\n", + "297884.6906814201\n", + "297990.4010389066\n", + "297991.8184011853\n", + "297843.59210133343\n", + "297849.61742355546\n", + "297843.3296328305\n", + "297851.64138312626\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297878.48688584194\n", + "297877.26916031435\n", + "297861.6248032213\n", + "297877.9192506703\n", + "297882.23031919455\n", + "297882.48632113374\n", + "297682.7134831972\n", + "297682.089354321\n", + "297687.4857736281\n", + "297688.81902426924\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297695.8284998467\n", + "297699.7247819663\n", + "297870.927987388\n", + "297871.1784749899\n", + "297675.3100402605\n", + "297675.32002897706\n", + "297680.8510747527\n", + "297681.2169366217\n", + "297818.3441170832\n", + "297830.5779204735\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297897.4247881161\n", + "297897.3853873843\n", + "298000.8648458956\n", + "298002.8834382631\n", + "297662.8972880637\n", + "297662.94890095154\n", + "297879.78267807333\n", + "297878.758575974\n", + "297875.23820368946\n", + "297876.9171598256\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297857.4993652791\n", + "297857.74874913046\n", + "297923.8219869069\n", + "297906.0014449664\n", + "297869.2765840404\n", + "297869.8202580062\n", + "297667.41689957544\n", + "297666.2726446527\n", + "297929.0469079929\n", + "297919.43983434606\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297841.42672612274\n", + "297841.428563327\n", + "297725.4941889024\n", + "297746.8292849163\n", + "298005.0658048237\n", + "297991.6020628827\n", + "297703.11795634637\n", + "297703.22332080087\n", + "297670.5272987561\n", + "297672.6552523632\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297790.31036385434\n", + "297791.1882601214\n", + "297734.96686328074\n", + "297734.42418867705\n", + "297857.6170376312\n", + "297857.67671133054\n", + "297858.4263769901\n", + "297860.98504483904\n", + "297595.9296461901\n", + "297598.40003632946\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297786.4055796488\n", + "297781.9919009066\n", + "297747.8131033477\n", + "297748.854588725\n", + "297750.9107581858\n", + "297744.8037084621\n", + "297717.0446045399\n", + "297704.1849323827\n", + "297635.7046404412\n", + "297632.3431910873\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297851.5196765106\n", + "297852.28032813553\n", + "298049.29283302807\n", + "298046.2920077925\n", + "297810.36258130637\n", + "297804.0715255321\n", + "297810.62752011174\n", + "297810.6721442733\n", + "297761.49498756113\n", + "297773.2665988916\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297682.42591778457\n", + "297687.89883430296\n", + "297899.8962933522\n", + "297917.2027506334\n", + "297902.94355890626\n", + "297900.3484988393\n", + "297645.0569821463\n", + "297645.144195157\n", + "297938.23268991767\n", + "297948.391983537\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297795.3593098301\n", + "297798.146521469\n", + "297841.1143137535\n", + "297854.76299137477\n", + "297639.75045728113\n", + "297624.1634999127\n", + "297897.12968747015\n", + "297890.68079654156\n", + "297833.1690416312\n", + "297834.3789830475\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297787.4594662098\n", + "297787.4801672243\n", + "297654.6009651448\n", + "297653.26686500234\n", + "297903.835497173\n", + "297888.9113997851\n", + "297979.46423988335\n", + "297979.46709206956\n", + "297900.724776942\n", + "297900.17688515515\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297846.4654198513\n", + "297845.4256977265\n", + "297771.86446410517\n", + "297774.22537649085\n", + "297786.412651436\n", + "297787.84623181267\n", + "297855.82549200446\n", + "297858.8303840299\n", + "297922.95101790706\n", + "297924.7636991326\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297952.5206365282\n", + "297934.9498971468\n", + "297670.15126412985\n", + "297669.8967631787\n", + "298002.2278905284\n", + "298002.5011960581\n", + "297939.3651208804\n", + "297934.09579168196\n", + "297837.73592244997\n", + "297838.0886382757\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297781.85971349326\n", + "297782.78877431026\n", + "297830.3365796945\n", + "297832.58120353916\n", + "297939.31497045234\n", + "297952.37159719743\n", + "297790.85859437106\n", + "297789.65916577575\n", + "297698.37665633066\n", + "297696.10806787346\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297770.8977109762\n", + "297771.4965650944\n", + "297818.4520839529\n", + "297830.7066914969\n", + "297871.39061017503\n", + "297871.35383744084\n", + "297787.1739619725\n", + "297796.9708252887\n", + "298001.4281886694\n", + "298002.1342161055\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297576.74811287085\n", + "297577.4458165782\n", + "297845.2281149602\n", + "297838.58987423405\n", + "297676.90077148477\n", + "297699.7778032818\n", + "297658.6003595596\n", + "297656.4919623783\n", + "297968.54347431473\n", + "297989.34654361167\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297988.8276019365\n", + "297989.37556919444\n", + "297972.23882414773\n", + "297971.35291080544\n", + "297782.58099910215\n", + "297781.98696006305\n", + "297561.2931249806\n", + "297574.2772458021\n", + "297937.5138328191\n", + "297937.5715055586\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297869.249691058\n", + "297876.43057766533\n", + "297727.49872434436\n", + "297728.0054945473\n", + "297689.2556171461\n", + "297703.7946065728\n", + "297727.7138624414\n", + "297729.6452512909\n", + "297901.8006044905\n", + "297902.63657806587\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297936.83026424394\n", + "297936.89312606823\n", + "298070.58113290113\n", + "298072.82110562717\n", + "298016.3417074623\n", + "298012.54585395666\n", + "297823.1326106637\n", + "297813.1415112117\n", + "297820.45031760196\n", + "297816.1087950966\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297955.3088932919\n", + "297955.5896459048\n", + "297887.49754861475\n", + "297887.9476245084\n", + "297992.4179241086\n", + "297989.7517770145\n", + "297839.52663457795\n", + "297848.46773940604\n", + "297652.31051661086\n", + "297653.25810115156\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297606.3068218656\n", + "297610.4464654693\n", + "297896.7665542569\n", + "297902.306201965\n", + "297846.4195521619\n", + "297843.55587141897\n", + "297750.16690169694\n", + "297750.1674092018\n", + "298002.1700131029\n", + "297996.08788904134\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297867.0873256635\n", + "297855.98345439613\n", + "297752.6686227003\n", + "297748.3642315042\n", + "297588.54953732825\n", + "297588.1941807897\n", + "297696.942778959\n", + "297702.4672522066\n", + "297747.5721213854\n", + "297748.0402054583\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297745.9207783303\n", + "297741.77457842365\n", + "297810.4208934099\n", + "297822.9912333261\n", + "297930.67699255684\n", + "297936.4331764121\n", + "297706.0402219755\n", + "297707.0715960022\n", + "297858.00060865114\n", + "297858.07038631657\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297862.0369640973\n", + "297860.6637658194\n", + "297728.2790382507\n", + "297733.5534096006\n", + "297784.6119180462\n", + "297784.91815034597\n", + "297838.2170141946\n", + "297824.4625903157\n", + "297852.1331544906\n", + "297854.00880690245\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298010.80570620304\n", + "298012.3849358097\n", + "297912.26950869226\n", + "297911.39562959434\n", + "297700.4604114597\n", + "297702.6090967786\n", + "297814.60369342053\n", + "297815.59101793123\n", + "297779.43681610713\n", + "297797.3931197056\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297787.8753587233\n", + "297788.3665481457\n", + "297721.22406494507\n", + "297744.7262827493\n", + "297690.74669260264\n", + "297690.545916212\n", + "297883.20436694013\n", + "297880.8412253179\n", + "297743.48062656797\n", + "297740.54744062095\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297904.5315229395\n", + "297904.00260044745\n", + "297947.8647002288\n", + "297976.81123494625\n", + "297899.0797681975\n", + "297888.524219817\n", + "297740.7802771424\n", + "297746.5309268305\n", + "298008.19212877046\n", + "298008.51081525174\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297733.1519700739\n", + "297717.28982229315\n", + "297974.41107924585\n", + "297970.61994149577\n", + "297775.50199018186\n", + "297775.50570795615\n", + "297925.56870996277\n", + "297925.63918193814\n", + "297816.7794922988\n", + "297817.370905605\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297963.18677686976\n", + "297964.66192833136\n", + "297956.9451090644\n", + "297957.0389249298\n", + "297996.8031529423\n", + "297993.22482067463\n", + "297795.2315503212\n", + "297796.79312216\n", + "297787.13458776195\n", + "297803.45331510174\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297822.7420018244\n", + "297823.4067658414\n", + "297802.34795515874\n", + "297805.44156361965\n", + "297848.61351235886\n", + "297859.9100933553\n", + "297851.21924899245\n", + "297853.6957931402\n", + "297849.00517422816\n", + "297849.7509556247\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297867.48931331676\n", + "297867.9249069232\n", + "297805.05408026435\n", + "297802.71980054694\n", + "297702.9285051604\n", + "297694.44204926875\n", + "297598.36436600756\n", + "297601.71620167256\n", + "297810.85721167\n", + "297808.2018587828\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297912.37303993845\n", + "297915.42853168544\n", + "297714.8082562085\n", + "297717.1672559369\n", + "297795.22031122627\n", + "297806.22950786963\n", + "297502.9278987768\n", + "297491.8952699946\n", + "297641.8923187292\n", + "297630.8179033911\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297745.8615183893\n", + "297763.52063841926\n", + "297956.8312543347\n", + "297948.3609907149\n", + "297848.62264004024\n", + "297833.04886273056\n", + "297631.0027514088\n", + "297630.5289728516\n", + "297687.2346966432\n", + "297706.19675024966\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297799.7412790129\n", + "297785.6917745255\n", + "297898.5869564719\n", + "297896.04451562464\n", + "297903.3831473692\n", + "297904.29920065234\n", + "297800.67409419344\n", + "297802.29419838556\n", + "297604.3286473392\n", + "297605.5711014215\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "298137.3203818086\n", + "298149.72237056866\n", + "297939.42715173727\n", + "297942.9880602429\n", + "297806.58599037724\n", + "297807.581520154\n", + "297759.12655121717\n", + "297759.56256901845\n", + "297700.50001386413\n", + "297701.8783833377\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297761.84020640864\n", + "297761.95720391534\n", + "297736.1352706693\n", + "297733.9260160902\n", + "297841.19286626717\n", + "297816.76178200886\n", + "297762.92646715074\n", + "297758.0188301735\n", + "297883.9272523655\n", + "297892.95766301104\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297979.97234978696\n", + "298000.50722633075\n", + "297829.8325900021\n", + "297834.9790012916\n", + "297836.3890804223\n", + "297834.62947311136\n", + "297890.323209075\n", + "297889.87727864936\n", + "297836.68232961063\n", + "297836.67439561745\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297933.9186668746\n", + "297935.0971485532\n", + "297920.32063205383\n", + "297919.8222650849\n", + "297672.3217454265\n", + "297671.6430106336\n", + "297944.33577403537\n", + "297952.02316441975\n", + "297857.37675158324\n", + "297872.8051727322\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297527.12086374295\n", + "297553.5372506021\n", + "297852.4781908248\n", + "297844.1210657298\n", + "297811.68238952657\n", + "297819.40986400604\n", + "297721.9916902169\n", + "297735.44155265286\n", + "297728.7253433019\n", + "297729.12935634423\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297686.02004838444\n", + "297691.27941453556\n", + "297763.87944786134\n", + "297764.4426157133\n", + "297901.4456209572\n", + "297899.2708817964\n", + "298017.6146025836\n", + "298020.44198115304\n", + "297854.23693771905\n", + "297866.2126222523\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297643.2096800559\n", + "297662.8842660302\n", + "297980.9156148586\n", + "297981.1453015948\n", + "297535.6703617241\n", + "297535.85554015305\n", + "297798.3210324418\n", + "297801.28338228614\n", + "297807.76951663115\n", + "297805.16012033715\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297852.6487041951\n", + "297852.9452499775\n", + "298044.11734721245\n", + "298040.3845580747\n", + "297658.940078158\n", + "297654.39180331235\n", + "297901.4118718524\n", + "297901.65318731905\n", + "297652.8197462353\n", + "297669.46072862466\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297731.2407815109\n", + "297733.33163274906\n", + "297948.98610927537\n", + "297948.9380380245\n", + "297559.64294045593\n", + "297565.63523386745\n", + "297643.4375461066\n", + "297639.77820057364\n", + "297738.3708366012\n", + "297751.9970195111\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297843.4171212666\n", + "297843.4996916417\n", + "297766.7184848472\n", + "297766.3648794617\n", + "297873.7502213994\n", + "297859.8963420865\n", + "297727.45048783976\n", + "297728.88160147547\n", + "297838.0660659515\n", + "297841.2388297256\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297779.0987952962\n", + "297781.21150815097\n", + "298027.8281276408\n", + "298027.83466079045\n", + "297808.17663718166\n", + "297807.2255635384\n", + "297828.5958925522\n", + "297856.6270085426\n", + "297782.1016427174\n", + "297784.90790483303\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297568.11804956524\n", + "297570.50636379374\n", + "297773.42299645726\n", + "297775.44742992864\n", + "297851.4449678316\n", + "297851.9287208101\n", + "297788.5170428059\n", + "297788.7170192157\n", + "297959.1134390044\n", + "297944.49065747875\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297822.8030986388\n", + "297822.42051943694\n", + "297903.25914697675\n", + "297902.16998559807\n", + "297757.6983074743\n", + "297767.681049791\n", + "297722.54256250535\n", + "297717.8697672653\n", + "297865.3353007822\n", + "297861.9068031107\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297873.56480158964\n", + "297870.5351091524\n", + "297710.1643665522\n", + "297726.8696422536\n", + "298045.9038442033\n", + "298047.64879245596\n", + "297902.89058956155\n", + "297911.44592174335\n", + "297740.50209363375\n", + "297723.6387324865\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297777.9432418668\n", + "297792.2296957629\n", + "297869.63735506625\n", + "297865.76261431666\n", + "297737.00807548774\n", + "297740.42433460604\n", + "297940.8603827638\n", + "297927.76305919164\n", + "298137.3442387922\n", + "298137.41287515225\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297821.84170788777\n", + "297822.6460023765\n", + "297896.29702968796\n", + "297890.1897917315\n", + "297691.6436361002\n", + "297691.63355655904\n", + "297660.9498310189\n", + "297664.7050336342\n", + "297855.60570590914\n", + "297847.9895306956\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", + "297547.9847490944\n", + "297537.4957312244\n", + "298060.7393777117\n", + "298060.7618112738\n", + "297873.82458943146\n", + "297873.85356912285\n", + "297839.8042942302\n", + "297830.1263980091\n", + "297520.5279220174\n", + "297514.01925984985\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22, 203)\n", + "297672.8967474278\n", + "297673.23428507766\n", + "297861.8350680059\n", + "297846.39122335566\n", + "297839.99318561575\n", + "297840.56383983896\n", + "297692.9585121496\n", + "297688.5535658027\n", + "297818.77499847737\n", + "297818.98953200254\n", + "empty in 10\n", + "empty in 11\n", + "empty in 12\n", + "empty in 13\n", + "empty in 14\n", + "empty in 15\n", + "empty in 16\n", + "empty in 17\n", + "empty in 18\n", + "empty in 19\n", + "empty in 20\n", + "empty in 21\n", + "(22,)\n", "bo1\n" ] } @@ -2157,25 +11492,31 @@ " with open(r\"{}/{}/data/CLs/{}-{}_{}s--CLs_Nll_list.pkl\".format(_dir, job, mi,ma,ste), \"rb\") as input_file:\n", " _Nll_list = pkl.load(input_file)\n", " \n", + "# print(_Nll_list)\n", + " \n", " if bo5: \n", " for s in range(2*ste):\n", - " Nll_list[s].append(np.min(_Nll_list[s]))\n", + " if _Nll_list[s]: \n", + " Nll_list[s].append(np.min(_Nll_list[s]))\n", + " print(np.min(_Nll_list[s]))\n", + " else:\n", + " print('empty in {}'.format(s))\n", " else:\n", " for s in range(2*ste):\n", " Nll_list[s].extend(_Nll_list[s])\n", " \n", - " with open(r\"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl\".format(_dir, job, mi,ma,ste), \"rb\") as input_file:\n", - " _CLs_values = pkl.load(input_file)\n", + "# with open(r\"{}/{}/data/CLs/{}-{}_{}s--CLs_list.pkl\".format(_dir, job, mi,ma,ste), \"rb\") as input_file:\n", + "# _CLs_values = pkl.load(input_file)\n", " \n", - " for s in range(ste):\n", - " CLs_values[s].extend(_CLs_values[s])\n", + "# for s in range(ste):\n", + "# CLs_values[s].extend(_CLs_values[s])\n", " \n", " print(np.shape(Nll_list))" ] }, { "cell_type": "code", - "execution_count": 50, + "execution_count": 49, "metadata": {}, "outputs": [], "source": [ @@ -2185,11 +11526,11 @@ "# for s in range(2*ste):\n", "# Nll_list[s] = [np.min(Nll_list[s])]\n", "\n", - "if bo5: \n", + "if bo5 and load: \n", " CLs_values= []\n", " for i in range(int(len(Nll_list)/2)):\n", " CLs_values.append([])\n", - " for j in range(len(Nll_list[0])):\n", + " for j in range(len(Nll_list[2*i])):\n", " CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j])\n", "\n", "\n", @@ -2202,12 +11543,12 @@ " with open(\"{}/{}-{}_{}s--CLs_Nll_list.pkl\".format(dirName, mi,ma,ste), \"wb\") as f:\n", " pkl.dump(Nll_list, f, pkl.HIGHEST_PROTOCOL)\n", " \n", - " CLs_values = []\n", + "# CLs_values = []\n", " \n", - " for i in range(int(len(Nll_list)/2)):\n", - " CLs_values.append([])\n", - " for j in range(nr_of_toys):\n", - " CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j])\n", + "# for i in range(int(len(Nll_list)/2)):\n", + "# CLs_values.append([])\n", + "# for j in range(nr_of_toys):\n", + "# CLs_values[i].append(Nll_list[2*i][j]-Nll_list[2*i+1][j])\n", "\n", " with open(\"{}/{}-{}_{}s--CLs_list.pkl\".format(dirName, mi,ma,ste), \"wb\") as f:\n", " pkl.dump(CLs_values, f, pkl.HIGHEST_PROTOCOL)" @@ -2215,7 +11556,7 @@ }, { "cell_type": "code", - "execution_count": 51, + "execution_count": 50, "metadata": {}, "outputs": [], "source": [ @@ -2232,12 +11573,12 @@ }, { "cell_type": "code", - "execution_count": 56, + "execution_count": 51, "metadata": {}, "outputs": [ { "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAEICAYAAABPgw/pAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAdg0lEQVR4nO3dfXRV9Z3v8fe3PEWvUafCzBSiJmNBBdEoQeNSMFVU1PjQCgpoC1rJdVXuaGXNEscOUi619AG1Xmm9VC1eRwyWagUGH6ZWKq1SEzQgD5KC4hgjiEgZfAiKfu8f50APyQk5wNnZyf59Xmtlec7e+5zz2QKf/LKz92+buyMiIp3fl+IOICIi+aFCFxFJCBW6iEhCqNBFRBJChS4ikhAqdBGRhFChS5DMbIqZ/XvcOUTySYUu7cbMxphZrZl9aGbvmtlTZnZmel2LgjWzxWZ2XTxp88fMzjGz183sYzN73syOzuE1Z5mZm9m0jGU9zOwuM2s0s61m9nMz6xZteulMVOjSLszsZuBu4A7gH4CjgJ8Dl8aZK2pm1hN4HPg34MtALTC3jdd0A34G/LnZqklAGXAC0A84BfheniNLJ6ZCl8iZ2WHAVOAGd3/c3T9y98/cfYG7/4uZDQf+FbgyPXpfbmY/AIYA96aX3ZvlfZ82swnNli03s2+kH//MzN42s/82s2VmNqSVfBVm1tBs2QYzG5Z+/CUzm2Rm681si5k9ZmZfznH3vwGscvdfu3sTMAU4ycyO28trJgLPAq83W34xcI+7f+Dum4F7gGtzzCEBUKFLezgdKACeyLbS3Z8mNXKf6+6HuPtJ7n4bsASYkF42IctL5wCjdz0xs/7A0cB/pBfVAKWkRsZzgF+bWcF+5P9n4DLgLKA3sBWYmfG5K8xsTCuvHQAsz9jXj4D16eUtpA/HXEvqG2CL1emvzOdF6W+YIip0aRdHAO+7+848v+8TQGnGMemrgMfdfQeAu/+7u29x953uPgPoARy7H5/zP4Hb3L0h/d5TgBFm1jX9OSe6+5xWXnsIsK3Zsm1AYSvb3wP8m7t/mGXdU8CNZtbLzP6R1DcagINz3xVJMhW6tIctQM9dBZgv7r6d1Gh8VHrRKOCRXevNbKKZrTGzbWb2V+AwoOd+fNTRwBNm9tf0+6wBPif1u4C2fAgc2mzZocD25hua2cVAobu3doz9B8CrQB3wIvBb4DPgvVx2QpJPhS7t4SWgidRhi9Zkm/Yzl6lAHwVGm9npwEHA8wDp4+W3AFcAf+fuh5MaGVuW9/iIjFGumXUBemWsfxu4wN0Pz/gqcPd3csi3Cjgp473/B3BMenlz5wBlZrbRzDYCVwI3mdmTAO7+ibtPcPc+7v5PpL5RLnP3z3PIIQFQoUvk3H0bMBmYaWaXmdnBZtbNzC4wsx+nN9sEFJtZ5t/JTcA/tfH2i0iNoKeSOgb/RXp5IbAT2Ax0NbPJtBwp71IPFJjZRekzTL5H6vDMLvcBP9h1aCd9yCPXs3OeAE4ws8vTx+8nAyvcvfkvPCF1Jkw/Usf9S4H5wC+Ba9Kf28fMeltKeXr723PMIQFQoUu7cPc7gZtJleVmUqPeCaQOGwD8Ov3fLWb2Svrxz0gdq95qZve08r47SJ0WOIzULz53eYbUMed64C1SPyG83cp7bAO+A9wPvENqxJ551svPSJXrs2a2HVgKnLZrpZmtMrOrWnnvzcDlpA6XbE2/blTGa+8zs/vS22539427voBPgI/c/YP05seQOtTyEfAQMMndn832uRIm0w0uRESSQSN0EZGEUKGLiCSECl1EJCFU6CIiCZHXCz32Rc+ePb24uDiuj5dQNTZC795xpxDZb8uWLXvf3XtlWxdboRcXF1NbWxvXx0uoli2DQYPiTiGy38zsrdbW6ZCLhKWwtSlURDo/FbqEpbIy7gQikVGhS1jq6+NOIBKZ2I6hi8RiypTUl7Tw2Wef0dDQQFNTU9xRBCgoKKCoqIhu3XK/y6AKXUQAaGhooLCwkOLiYsyyTUop7cXd2bJlCw0NDZSUlOT8Oh1ykbBodN6qpqYmjjjiCJV5B2BmHHHEEfv801KbhW5mD5rZe2a2spX1Zmb3mNm69K24TtmnBCLtqV+/uBN0aCrzjmN//ixyGaHPBobvZf0FQN/0VxXwi31OIdJeFi6MO4FIZNo8hu7uL5hZ8V42uRT4f56ah3epmR1uZl9x93fzlFEkf7a3uPObtKJ40n+0vdE+2DD9oja32bhxIzfddBM1NTX06NGD4uJi7r77brp3786LL77ImDGpe3HX1dXR2NjIhRdemPV9Ro8ezapVq7jmmmvYunUrQ4cOZdiwYQeUf/Hixfz0pz9lYbNBQVtZWvPDH/6QBx54gC5dunDPPfdw/vnnH1A+yM8vRfuw540DGtLLWhS6mVWRGsVz1FFH5eGjgSkZNzyf0vxevNKRZBZELv+4I/msqqrU1aLNZfw9Km7a837P+5p1j88uGJPxGe3497MT/rtwd77+9a8zduxYqqurgVRZbtq0ic8//5w5c+bsUei1tbVZS3Tjxo28+OKLvPVWqxdU5tXesrRm9erVVFdXs2rVKhobGxk2bBj19fV06dLlgLLk45ei2Q70ZL1rhrvPcvcydy/r1SvrVAQi0cpW5tIhPP/883Tr1o3rr79+97LS0lKGDBnCpEmTWLJkCaWlpfzoRz9i8uTJzJ07l9LSUubO3fOe2ueddx7vvfcepaWlLFmyhHHjxjFv3jy2bdvGsccey9q1a4HUKP6Xv/wlAM8++yynn346p5xyCiNHjuTDDz8E4Omnn+a4447jzDPP5PHHH2+R+dNPP22R5YMPPuCyyy7jxBNPpLy8nBUrVrR43ZNPPsmoUaPo0aMHJSUlfPWrX+Xll18+4P+H+Sj0BuDIjOdFQGMe3lck/yZOjDuBtGLlypUMamWenenTpzNkyBDq6uq45ZZbmDp1KldeeSV1dXVceeWVe2w7f/58jjnmGOrq6hgyZMju5Ycddhj33nsv48aNo7q6mq1btzJ+/Hjef/99pk2bxu9+9zteeeUVysrKuPPOO2lqamL8+PEsWLCAJUuWsHHjxha5unfv3iLL7bffzsknn8yKFSu44447+Na3vtXide+88w5HHvm32iwqKuKdd3K55/je5aPQ5wPfyrhx7TYdP5cOSzMtBu3cc89l4MCB3HDDDdx///0ALF26lNWrV3PGGWdQWlrKQw89xFtvvcXrr79OSUkJffv2xcy4+uqrc/qMP/7xj3zzm98E4Oyzz2bLli1s27bnYa9st/7MxxlGbR5DN7NHgQqgp5k1kLrLeLd0qPtI3XX9QmAd8DHpO5SLdEgaoXdYAwYMYN68eZF+xhdffMGaNWs46KCD+OCDDygqKsLdOffcc3n00Uf32Laurm6/SjaXsi4qKuLtt//2q8eGhgZ652Gw0eYI3d1Hu/tX3L2buxe5+wPufl+6zPGUG9z9GHcf6O6aE1c6Lo3QO6yzzz6bHTt27D6uDVBTU8Mf/vAHCgsL2Z5xhlLz57m66667OP7443n00Ue59tpr+eyzzygvL+dPf/oT69atA+Djjz+mvr6e4447jjfffJP169cDtCj81rIMHTqURx55BEidGdOzZ08OPfTQPV5zySWXUF1dzY4dO3jzzTf5y1/+wqmnnrrP+9OcLv2XsGgO/pxFfSZSc2bGE088wU033cT06dMpKCjYfdpicXExXbt25aSTTmLcuHGMHTuW6dOnU1payq233triOHo29fX13H///bz88ssUFhYydOhQpk2bxve//31mz57N6NGj2bFjBwDTpk2jX79+zJo1i4suuoiePXty5plnsnJly+srv/a1r+2RZcqUKVxzzTWceOKJHHzwwTz00EMtXjNgwACuuOIK+vfvT9euXZk5c+YBn+ECYNl+PGgPZWVlnpcbXHTC07NC1SFOW1y8GCoqWr5Apy2yZs0ajj/++IgCyf7I9mdiZsvcvSzb9prLRcKiuVwkwVToEpbFi+NOIBIZFbqEpaoq7gQikVGhS1jKsh56FEkEFbqERSN0STAVuoSlsDDuBCKR0XnoEpZGTTOUs8xTH/Pyfm2fPhnF9LnLly+nsrKSESNG7HPk2bNnc9555+2+ivO6667j5ptvpn///vv8Xu1BI3QJi85y6bB2TZ9bUVHB+vXrWb16NXfccQebNm1iw4YNzJnzt+sD6urqWLRoUdb32TV97ooVK/jud797QJlmz55NY8Yg4P777++wZQ4qdAnNrFlxJ5BWRDV9bqbnnnuOk08+mYEDB3LttdfuvjJ06tSpDB48mBNOOIGqqircnXnz5lFbW8tVV11FaWkpn3zyCRUVFey6IPKQQw7htttu46STTqK8vJxNmzYBsH79esrLyxk8eDCTJ0/mkEMOifJ/2x5U6BKWBQviTiCtiHr63KamJsaNG8fcuXN57bXX2LlzJ7/4ReqOmRMmTKCmpoaVK1fyySefsHDhQkaMGEFZWRmPPPIIdXV1HHTQQXt8zkcffUR5eTnLly9n6NChu+egufHGG7nxxhupqanJy4Rb+0KFLmEZM6btbSSR1q5dS0lJCf3SNwofO3YsL7zwApD66eC0005j4MCB/P73v2fVqlVtvl/37t2prKwEYNCgQWzYsAGAl156iZEjRwLsPubfXlToEpb0P0DpeAYMGMCyCO8o1dq8VU1NTXznO99h3rx5vPbaa4wfP56mpqY2369bt267p8Xt0qULO3fuzGve/aFCl7BohN5hRT197nHHHceGDRt2T5P78MMPc9ZZZ+0u7549e/Lhhx/uMSf7/nxOeXk5v/nNbwB23xu1vei0RQmLGcQ0w2in086zl0Y9fW5BQQG/+tWvGDlyJDt37mTw4MFcf/319OjRg/HjxzNw4ECKi4sZPHjw7teMGzeO66+/noMOOoiXXnopp/24++67ufrqq5kxYwYXXXQRhx2W59M/90KFLmFRmXdovXv35rHHHsu67rnnntvjeU1NTdbtiouL95i3fPbs2bsfn3POObz66qstXjNt2jSmTZvWYvnll1/O5Zdfvvv54ozTXnfdSBpgxIgRu89z79OnD0uXLsXMqK6upqwdp5tQoUtY5szRYReJ1LJly5gwYQLuzuGHH86DDz7Ybp+tQpewLFyoQpdIDRkyhOXLl8fy2fqlqIRlzpy2twlYXHcwk5b2589ChS5hufjiuBN0WAUFBWzZskWl3gG4O1u2bKGgoGCfXqdDLhIWTZ/bqqKiIhoaGti8eXPcUYTUN9iioqJ9eo0KXcKS7QbRAqQulCkpKYk7hhwAHXKRsLTz3Boi7UmFLmHZx6v+RDoTFbqERdPnSoKp0CUs6bmsRZJIhS5h0QhdEkyFLmHRWS6SYCp0CcuUKXEnEImMCl3Ckr5bjUgSqdAlLO04lalIe8up0M1suJmtNbN1ZjYpy/qjzOx5M3vVzFaY2YX5jyqSB42NcScQiUybhW5mXYCZwAVAf2C0mfVvttn3gMfc/WRgFPDzfAcVyYsZM+JOIBKZXEbopwLr3P0Nd/8UqAYubbaNA4emHx8GaBgkHZNG6JJguRR6H+DtjOcN6WWZpgBXm1kDsAj4X9neyMyqzKzWzGo1o5vEQiN0SbBcCt2yLGs+YfJoYLa7FwEXAg+bWYv3dvdZ7l7m7mW9evXa97QiB2rQoLgTiEQml0JvAI7MeF5Ey0Mq3wYeA3D3l4ACoGc+Aorkla4UlQTLpdBrgL5mVmJm3Un90nN+s23+CzgHwMyOJ1XoOqYiHU9hYdwJRCLTZqG7+05gAvAMsIbU2SyrzGyqmV2S3mwiMN7MlgOPAuNc97GSjqiyMu4EIpHJ6Y5F7r6I1C87M5dNzni8Gjgjv9FEIlBfH3cCkcjoSlEJi+ZykQRToYuIJIQKXcKiEbokmApdwqLZFiXBVOgSloUL404gEhkVuoRl+/a4E4hERoUuYamqijuBSGRU6BKWZcviTiASGRW6hGXixLgTiERGhS5h6d077gQikVGhS1g0QpcEU6FLWDRClwRToUtYamvjTiASGRW6hEWzLUqCqdAlLJrLRRJMhS5hWbw47gQikVGhS1h0pagkmApdwlJWFncCkcio0CUsGqFLgqnQJSyFhXEnEImMCl3C0tgYdwKRyKjQJSw6y0USTIUuYZk1K+4EIpFRoUtYFiyIO4FIZFToEpYxY+JOIBIZFbqEpbIy7gQikVGhS1g0QpcEU6FLWMziTiASGRW6hMU97gQikVGhS1jmzIk7gUhkVOgSloUL404gEhkVuoRFI3RJsJwK3cyGm9laM1tnZpNa2eYKM1ttZqvMTP9qpGO6+OK4E4hEpmtbG5hZF2AmcC7QANSY2Xx3X52xTV/gVuAMd99qZn8fVWCRA6LpcyXBchmhnwqsc/c33P1ToBq4tNk244GZ7r4VwN3fy29MkTypqIg7gUhkcin0PsDbGc8b0ssy9QP6mdmfzGypmQ3PV0CRvOrdO+4EIpFp85ALkO1KjOYn83YF+gIVQBGwxMxOcPe/7vFGZlVAFcBRRx21z2FFDtj27XEnEIlMLiP0BuDIjOdFQPO7BDQAT7r7Z+7+JrCWVMHvwd1nuXuZu5f16tVrfzOL7D9NnysJlkuh1wB9zazEzLoDo4D5zbb5LfA1ADPrSeoQzBv5DCqSF7W1cScQiUybhe7uO4EJwDPAGuAxd19lZlPN7JL0Zs8AW8xsNfA88C/uviWq0CL7TSN0SbBcjqHj7ouARc2WTc547MDN6S+RjquiQrehk8TSlaISlilT4k4gEhkVuoSlX7+4E4hERoUuYSkrizuBSGRU6BKWxuZn3IokhwpdwjJjRtwJRCKjQpewaIQuCaZCl7BohC4JpkKXsAwaFHcCkcio0CUsulJUEkyFLmEpLIw7gUhkVOgSlsrKuBOIREaFLmGpr487gUhkVOgSFs3lIgmmQhcRSQgVuoRFI3RJMBW6hEWzLUqCqdAlLAsXxp1AJDIqdAnL9u1xJxCJjApdwlJVFXcCkcio0CUsy5bFnUAkMip0CcvEiXEnEImMCl3C0rt33AlEIqNCl7BohC4JpkKXsGiELgmmQpew1NbGnUAkMip0CYtmW5QEU6FLWDSXiySYCl3Csnhx3AlEIqNCl7DoSlFJMBW6hKWsLO4EIpFRoUtYNEKXBFOhS1gKC+NOIBIZFbqEpbEx7gQikcmp0M1suJmtNbN1ZjZpL9uNMDM3Mx2olI5JZ7lIgrVZ6GbWBZgJXAD0B0abWf8s2xUC/wz8Od8hRfJm1qy4E4hEJpcR+qnAOnd/w90/BaqBS7Ns97+BHwNNecwnkl8LFsSdQCQyuRR6H+DtjOcN6WW7mdnJwJHuvtcbNppZlZnVmlnt5s2b9zmsyAEbMybuBCKRyaXQLcsy373S7EvAXUCb85K6+yx3L3P3sl69euWeUiRfKivjTiASmVwKvQE4MuN5EZB5qkAhcAKw2Mw2AOXAfP1iVDokjdAlwXIp9Bqgr5mVmFl3YBQwf9dKd9/m7j3dvdjdi4GlwCXurnlKpeOxbD9wiiRDm4Xu7juBCcAzwBrgMXdfZWZTzeySqAOK5JV729uIdFJdc9nI3RcBi5otm9zKthUHHkskInPm6LCLJJauFJWwLNzriVginZoKXcIyZ07cCUQio0KXsFx8cdwJRCKjQpewaPpcSTAVuoSloiLuBCKRUaFLWHr3jjuBSGRU6BKW7dvjTiASGRW6hEXT50qCqdAlLLWakUKSS4UuYdEIXRJMhS5h0VkukmAqdAnLlClxJxCJjApdwtKvX9wJRCKjQpewlOm+K5JcKnQJS2Nj29uIdFIqdAnLjBlxJxCJjApdwqIRuiSYCl3CohG6JJgKXcIyaFDcCUQio0KXsOhKUUkwFbqEpbAw7gQikVGhS1gqK+NOIBIZFbqEpb4+7gQikVGhS1g0l4skmApdRCQhVOgSFo3QJcFU6BIWzbYoCaZCl7AsXBh3ApHIqNAlLNu3x51AJDIqdAlLVVXcCUQio0KXsCxbFncCkcio0CUsEyfGnUAkMjkVupkNN7O1ZrbOzCZlWX+zma02sxVm9pyZHZ3/qCJ50Lt33AlEItNmoZtZF2AmcAHQHxhtZv2bbfYqUObuJwLzgB/nO6hIXmiELgmWywj9VGCdu7/h7p8C1cClmRu4+/Pu/nH66VKgKL8xRfJEI3RJsFwKvQ/wdsbzhvSy1nwbeCrbCjOrMrNaM6vdvHlz7ilF8qW2Nu4EIpHJpdAtyzLPuqHZ1UAZ8JNs6919lruXuXtZr169ck8pki+abVESLJdCbwCOzHheBLS4066ZDQNuAy5x9x35iSeSZ5rLRRIsl0KvAfqaWYmZdQdGAfMzNzCzk4H/S6rM38t/TJE8Wbw47gQikWmz0N19JzABeAZYAzzm7qvMbKqZXZLe7CfAIcCvzazOzOa38nYi8dKVopJgXXPZyN0XAYuaLZuc8XhYnnOJRKOsLO4EIpHRlaISFo3QJcFU6BKWwsK4E4hERoUuYWlscYKWSGKo0CUsOstFEkyFLmGZNSvuBCKRUaFLWBYsiDuBSGRU6BKWMWPiTiASGRW6hKWyMu4EIpFRoUtYNEKXBFOhS1gs2+ShIsmgQpeweNaZn0USQYUuYZkzJ+4EIpFRoUtYFi6MO4FIZFToEhaN0CXBVOgSlosvjjuBSGRU6BIWTZ8rCaZCl7BUVMSdQCQyKnQJS+/ecScQiYwKXcKyfXvcCUQio0KXsGj6XEkwFbqEpbY27gQikVGhS1g0QpcEU6FLWHSWiySYCl3CMmVK3AlEIqNCl7D06xd3ApHIqNAlLGVlcScQiYwKXcLS2Bh3ApHIqNAlLDNmxJ1AJDIqdAmLRuiSYCp0CYtG6JJgKnQJy6BBcScQiYwKXcKiK0UlwVToEpbCwrgTiEQmp0I3s+FmttbM1pnZpCzre5jZ3PT6P5tZcb6DiuRFZWXcCUQi02ahm1kXYCZwAdAfGG1m/Ztt9m1gq7t/FbgL+FG+g4rkRX193AlEIpPLCP1UYJ27v+HunwLVwKXNtrkUeCj9eB5wjplZ/mKK5InmcpEEM3ff+wZmI4Dh7n5d+vk3gdPcfULGNivT2zSkn69Pb/N+s/eqAnbdpfdYYG2+dqQd9QTeb3OrZAltn0PbX9A+dyZHu3uvbCu65vDibCPt5t8FctkGd58FdOrTDMys1t2DmhAktH0ObX9B+5wUuRxyaQCOzHheBDS/3G73NmbWFTgM+CAfAUVEJDe5FHoN0NfMSsysOzAKmN9sm/nA2PTjEcDvva1jOSIikldtHnJx951mNgF4BugCPOjuq8xsKlDr7vOBB4CHzWwdqZH5qChDx6xTHzLaT6Htc2j7C9rnRGjzl6IiItI56EpREZGEUKGLiCSECj0HZvYTM3vdzFaY2RNmdnjGulvTUx6sNbPz48yZT2Y20sxWmdkXZlbWbF0i9xnanuYiCczsQTN7L339yK5lXzaz/zSzv6T/+3dxZsw3MzvSzJ43szXpv9c3ppcnar9V6Ln5T+AEdz8RqAduBUhPgTAKGAAMB36eniohCVYC3wBeyFyY5H3OcZqLJJhN6s8u0yTgOXfvCzyXfp4kO4GJ7n48UA7ckP6zTdR+q9Bz4O7PuvvO9NOlpM7Fh9SUB9XuvsPd3wTWkZoqodNz9zXunu1K3sTuM7lNc9HpufsLtLxOJHP6joeAy9o1VMTc/V13fyX9eDuwBuhDwvZbhb7vrgWeSj/uA7ydsa4hvSzJkrzPSd63tvyDu78LqfID/j7mPJFJzwZ7MvBnErbfuVz6HwQz+x3wj1lW3ebuT6a3uY3Uj26P7HpZlu07zXmguexztpdlWdZp9rkNSd43AczsEOA3wE3u/t9Jm0NQhZ7m7sP2tt7MxgKVwDkZV8HmMi1Ch9XWPreiU+9zG5K8b23ZZGZfcfd3zewrwHtxB8o3M+tGqswfcffH04sTtd865JIDMxsO3AJc4u4fZ6yaD4xK3+CjBOgLvBxHxnaU5H3OZZqLpMqcvmMs0NpPaJ1SejrvB4A17n5nxqpE7beuFM1BekqDHsCW9KKl7n59et1tpI6r7yT1Y9xT2d+lczGzrwP/B+gF/BWoc/fz0+sSuc8AZnYhcDd/m+biBzFHyjszexSoIDV97CbgduC3wGPAUcB/ASPdPTET7JnZmcAS4DXgi/TifyV1HD0x+61CFxFJCB1yERFJCBW6iEhCqNBFRBJChS4ikhAqdBGRhFChi4gkhApdRCQh/j/paS3vCad70QAAAABJRU5ErkJggg==\n", + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXAAAAEICAYAAABGaK+TAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+17YcXAAAcuklEQVR4nO3de3RV5bnv8e+zuQVLxCq0W4w21IoXvEQJGo+C1HsrXtpKFXQXtJLjqOyjlXOOWPdWdFCL+xS1bm07qFoY3XKpqBuhrdVaqbTeCDYgiKJUWmMEFJGCEhR9zh9rQlfCWmQlmSsza76/zxgZWWten8kKv7x555zvNHdHRERKzz8lXYCIiLSPAlxEpEQpwEVESpQCXESkRCnARURKlAJcRKREKcAlGGY22cz+K+k6ROKiAJeiMrMxZlZnZlvN7G0z+42ZnRzN2y1QzWyRmV2RTLXxMbPTzOwVM/vQzJ4ysy8UsM4pZuZmNiVrWi8zu8PMGs1sk5n92Mx6FLd6KRUKcCkaM7sWuBO4Ffg8cBDwY+D8JOsqNjPrBzwM/DuwL1AHzG1lnR7Aj4DnW8yaBFQDRwKDgOOAf4u5ZClRCnApCjPrC9wCXOXuD7v7B+7+sbsvcPf/Y2ZnA98DLopa58vM7PvAMODuaNrdObb7mJlNaDFtmZl9PXr9IzN708z+bmZLzWxYnvpGmFlDi2lrzez06PU/mdkkM1tjZhvN7Jdmtm+Bh/91YKW7P+juTcBk4BgzO2wP60wEHgdeaTH9XOAud3/P3d8B7gIuL7AOSTkFuBTLiUAZ8Eiume7+GJmW+Vx37+Pux7j7DcBiYEI0bUKOVWcBo3e+MbMjgC8Av4omLQGqyLR8ZwEPmllZO+r/X8AFwCnAAGATcE/Wfpeb2Zg86w4GlmUd6wfAmmj6bqLulcvJ/MLbbXb0lf2+IvoFKYFTgEux7Ae86+47Yt7uI0BVVp/yJcDD7r4dwN3/y903uvsOd58G9AIObcd+/idwg7s3RNueDFxoZt2j/Rzt7rPyrNsH2Nxi2magPM/ydwH/7u5bc8z7DXC1mfU3s38m84sFYK/CD0XSSgEuxbIR6Lcz8OLi7lvItLYvjiZdDDywc76ZTTSzVWa22czeB/oC/dqxqy8Aj5jZ+9F2VgGfkOnLb81WYO8W0/YGtrRc0MzOBcrdPV8f+feBPwP1wDPAfwMfAxsKOQhJNwW4FMuzQBOZboh8cg2FWcjwmLOB0WZ2ItAbeAog6u++Dvgm8Fl334dMy9dybOMDslqxZtYN6J81/03gK+6+T9ZXmbu/VUB9K4Fjsrb9GeDgaHpLpwHVZrbOzNYBFwHXmNl8AHff5u4T3P0Ad/8imV+MS939kwLqkJRTgEtRuPtm4EbgHjO7wMz2MrMeZvYVM/uPaLH1QKWZZf8crge+2Mrmf02mhXwLmT70T6Pp5cAO4B2gu5ndyO4t4Z1WA2Vmdk50Bci/kelu2emnwPd3dtVEXRiFXj3zCHCkmX0j6n+/EVju7i1PUELmSpVBZPrtq4BHgZ8Bl0X7PcDMBlhGTbT8TQXWISmnAJeicffbgWvJhOM7ZFq1E8h0AwA8GH3faGYvRq9/RKaveZOZ3ZVnu9vJXKZ3OpkTlTv9lkyf8Wrgr2T+AngzzzY2A98B7gXeItMiz74q5UdkwvRxM9sCPAecsHOmma00s0vybPsd4Btkuj82RetdnLXuT83sp9GyW9x93c4vYBvwgbu/Fy1+MJmukw+AmcAkd388134lPKYHOoiIlCa1wEVESpQCXESkRCnARURKlAJcRKRExXqTRWv69evnlZWVnblLkYzGRhgwIOkqRNpl6dKl77p7/5bTOzXAKysrqaur68xdimQsXQpDhiRdhUi7mNlfc01XF4qEoTzfMCQipUsBLmEYOTLpCkRipwCXMKxenXQFIrHr1D5wkcRMnpz5kmY+/vhjGhoaaGpqSroUAcrKyqioqKBHj8KemqcAFwlYQ0MD5eXlVFZWYpZr0EbpLO7Oxo0baWhoYODAgQWtoy4UCYNa3zk1NTWx3377Kby7ADNjv/32a9NfQwpwCcOgQUlX0GUpvLuOtn4WCnAJw8KFSVcgEjv1gUsYtuz2NDPJoXLSr1pfqA3WTj2n1WXWrVvHNddcw5IlS+jVqxeVlZXceeed9OzZk2eeeYYxYzLPjq6vr6exsZGvfvWrObczevRoVq5cyWWXXcamTZsYPnw4p59+eofqX7RoET/84Q9Z2KIB0Fot+fzgBz/gvvvuo1u3btx1112cddZZHapPAS5hqK3N3I2ZJTusCgkaiZ+787WvfY2xY8cyZ84cIBOO69ev55NPPmHWrFnNAryuri5naK5bt45nnnmGv/415w2LsdtTLfm8/PLLzJkzh5UrV9LY2Mjpp5/O6tWr6datW7vrUBeKhKFFeEvX8NRTT9GjRw+uvPLKXdOqqqoYNmwYkyZNYvHixVRVVXHbbbdx4403MnfuXKqqqpg7t/kzoM8880w2bNhAVVUVixcvZty4ccybN4/Nmzdz6KGH8uqrrwKZVvrPfvYzAB5//HFOPPFEjjvuOEaNGsXWrVsBeOyxxzjssMM4+eSTefjhh3er+aOPPtqtlvfee48LLriAo48+mpqaGpYvX77bevPnz+fiiy+mV69eDBw4kC996Uu88MILHfr3U4BLGCZOTLoCyWHFihUMyTNGzdSpUxk2bBj19fVcd9113HLLLVx00UXU19dz0UUXNVv20Ucf5eCDD6a+vp5hw4btmt63b1/uvvtuxo0bx5w5c9i0aRPjx4/n3XffZcqUKfzud7/jxRdfpLq6mttvv52mpibGjx/PggULWLx4MevWrdutrp49e+5Wy0033cSxxx7L8uXLufXWW/nWt76123pvvfUWBx544K73FRUVvPVWIc/Izk9dKBIGjUQYrDPOOIMHH3yQq666imXLlgHw3HPP8fLLL3PSSScBmVb1iSeeyCuvvMLAgQM55JBDALj00kuZPn16q/v44x//yEMPPQTAqaeeysaNG9m8eTN9+/bdtUyux1d29AogBbiEQS3wLmnw4MHMmzevqPv49NNPWbVqFb179+a9996joqICd+eMM85g9uzZzZatr69vV6gWEs4VFRW8+eY/nrHd0NDAgA42LNSFImFQC7xLOvXUU9m+ffuufmmAJUuW8Ic//IHy8nK2ZF091PJ9oe644w4OP/xwZs+ezeWXX87HH39MTU0Nf/rTn3j99dcB+PDDD1m9ejWHHXYYb7zxBmvWrAHYLeDz1TJ8+HAeeOABIHPlSr9+/dh7772brXPeeecxZ84ctm/fzhtvvMFrr73G8ccf3+bjyaYWuIRB49AXpLOvxjEzHnnkEa655hqmTp1KWVnZrssIKysr6d69O8cccwzjxo1j7NixTJ06laqqKq6//vrd+sFzWb16Nffeey8vvPAC5eXlDB8+nClTpnDzzTczY8YMRo8ezfbt2wGYMmUKgwYNYvr06Zxzzjn069ePk08+mRUrVuy23S9/+cvNapk8eTKXXXYZRx99NHvttRczZ87cbZ3BgwfzzW9+kyOOOILu3btzzz33dOgKFADL1fQvlurqatcDHSQRixbBiBHNJukyQli1ahWHH3540mVIllyfiZktdffqlsuqC0XCoLFQJIUU4BKGRYuSrkAkdgpwCUNtbdIViMROAS5hqN6t+1Ck5CnAJQxqgUsKKcAlDHoqvaSQrgOXMDQ2Jl1BaZjct/Vl2rS9za0uUozhZJctW8bIkSO58MIL21zyjBkzOPPMM3fdJXnFFVdw7bXXcsQRR7R5W8VWcAvczLqZ2Z/NbGH0fqCZPW9mr5nZXDPrWbwyRTpIV6F0STuHkx0xYgRr1qzh5Zdf5tZbb2X9+vWsXbuWWbNm7Vq2vr6eX//61zm3s3M42eXLl/Pd7363QzXNmDGDxqxf+Pfee2+XDG9oWxfK1cCqrPe3AXe4+yHAJuDbcRYmEqsCBiSSzles4WSzPfnkkxx77LEcddRRXH755bvuvLzlllsYOnQoRx55JLW1tbg78+bNo66ujksuuYSqqiq2bdvGiBEj2HkDYp8+fbjhhhs45phjqKmpYf369QCsWbOGmpoahg4dyo033kifPn2K+c+2S0EBbmYVwDnAvdF7A04Fdo5CMxO4oBgFisRiwYKkK5Acij2cbFNTE+PGjWPu3Lm89NJL7Nixg5/85CcATJgwgSVLlrBixQq2bdvGwoULufDCC6muruaBBx6gvr6e3r17N9vPBx98QE1NDcuWLWP48OG7xnC5+uqrufrqq1myZEmHB6hqi0Jb4HcC/xf4NHq/H/C+u++I3jcAB8Rcm0h8on5UCcurr77KwIEDGRQ91Hrs2LE8/fTTQKb1f8IJJ3DUUUfx+9//npUrV7a6vZ49ezJy5EgAhgwZwtq1awF49tlnGTVqFMCuPvvO0GqAm9lIYIO7Zz/SJNd4izkHVTGzWjOrM7O6d955p51linRQ9J9OupbBgweztIhPS8o31lNTUxPf+c53mDdvHi+99BLjx4+nqamp1e316NFj1zCx3bp1Y8eOHa2sUVyFtMBPAs4zs7XAHDJdJ3cC+5jZzqtYKoCcp/ndfbq7V7t7df/+/WMoWaQd1ALvkoo9nOxhhx3G2rVrdw0b+4tf/IJTTjllV1j369ePrVu3NhuTvD37qamp2fVAh53P9uwMrV5G6O7XA9cDmNkI4H+7+yVm9iBwIZlQHwvML2KdIh1jBp048mbJKuCyvzgVezjZsrIyfv7znzNq1Ch27NjB0KFDufLKK+nVqxfjx4/nqKOOorKykqFDh+5aZ9y4cVx55ZX07t2bZ599tqDjuPPOO7n00kuZNm0a55xzTrMn8RRTm4aTzQrwkWb2RTLhvS/wZ+BSd9++p/U1nKx0JRpOVsPJxuXDDz+kd+/emBlz5sxh9uzZzJ/fvjZtW4aTbdONPO6+CFgUvf4L0LHHSYh0llmz1I0iRbN06VImTJiAu7PPPvtw//33d8p+dSemhGHhQgW4FM2wYcN2PTC5M2ksFAlD1h190lxnPpVL9qytn4UCXMJw7rlJV9AllZWVsXHjRoV4F+DubNy4kbKysoLXUReKhEHDyeZUUVFBQ0MDukejaygrK6OioqLg5RXgEoYWDzSWjB49ejBw4MCky5B2UheKhKETx6cQ6SwKcAlDG++sEykFCnAJg4aTlRRSgEsYdAewpJACXMKgFrikkAJcwqCrUCSFFOAShsmTk65AJHYKcAlD9EQWkTRRgEsYqncbiVOk5CnAJQyNOR8YJVLSFOAShmnTkq5AJHYKcAmDWuCSQgpwCYNa4JJCCnAJw5AhSVcgEjsFuIRBd2JKCinAJQzl5UlXIBI7BbiEYeTIpCsQiZ0CXMKwenXSFYjETgEuYdBYKJJCCnARkRKlAJcwqAUuKaQAlzBoNEJJIQW4hGHhwqQrEImdAlzCoKfSSwopwCUMtbVJVyASOwW4hGHp0qQrEImdAlzCMHFi0hWIxE4BLmEYMCDpCkRipwCXMKgFLimkAJcwqAUuKaQAlzDU1SVdgUjsFOASBo1GKCmkAJcwaCwUSaFWA9zMyszsBTNbZmYrzezmaPpAM3vezF4zs7lm1rP45Yq006JFSVcgErtCWuDbgVPd/RigCjjbzGqA24A73P0QYBPw7eKVKdJBuhNTUqjVAPeMrdHbHtGXA6cC86LpM4ELilKhSByqq5OuQCR2BfWBm1k3M6sHNgBPAGuA9919R7RIA3BAcUoUiYFa4JJC3QtZyN0/AarMbB/gEeDwXIvlWtfMaoFagIMOOqidZYp0UHn5biMSri0bk/Vuc+fWIxKDNl2F4u7vA4uAGmAfM9v5C6ACaMyzznR3r3b36v79+3ekVpH2a8z54ylS0gq5CqV/1PLGzHoDpwOrgKeAC6PFxgLzi1WkSIfpKhRJoUJa4PsDT5nZcmAJ8IS7LwSuA641s9eB/YD7ilemSAdNn550BSKxa7UP3N2XA8fmmP4X4PhiFCUSuwULkq5AJHa6E1PCMGZM68uIlBgFuIRh5MikKxCJnQJcwqAWuKSQAlzCYJZ0BSKxU4BLGDznfWYiJU0BLmGYNSvpCkRipwCXMCxcmHQFIrFTgEsY1AKXFFKASxjOPTfpCkRipwCXMGg4WUkhBbiEYcSIpCsQiZ0CXMIwYEDSFYjETgEuYWjxMAeRNFCASxg0nKykkAJcwlBXl3QFIrFTgEsY1AKXFFKASxh0FYqkkAJcwjB5ctIViMROAS5hGDQo6QpEYqcAlzBUVyddgUjsFOAShsbGpCsQiZ0CXMIwbVrSFYjETgEuYVALXFKoe9IFiHSKqAVeOelXuyatLUuqGJF4qAUuYRgyJOkKRGKnAJcw6E5MSSEFuIShvDzpCkRipwCXMIwcmXQFIrFTgEsYVq9OugKR2CnAJQwaC0VSSAEuIlKiFOASBrXAJYUU4BIGjUYoKaQAlzAsXJh0BSKxU4BLGPRUekkhBbiEobY26QpEYqcAlzAsXZp0BSKxU4BLGCZOTLoCkdgpwCUMAwYkXYFI7FoNcDM70MyeMrNVZrbSzK6Opu9rZk+Y2WvR988Wv1yRdlILXFKokBb4DmCiux8O1ABXmdkRwCTgSXc/BHgyei/SNakFLinUaoC7+9vu/mL0eguwCjgAOB+YGS02E7igWEWKdFhdXdIViMSuTX3gZlYJHAs8D3ze3d+GTMgDn8uzTq2Z1ZlZ3TvvvNOxakXaS6MRSgoVHOBm1gd4CLjG3f9e6HruPt3dq929un///u2pUaTjNBaKpFBBAW5mPciE9wPu/nA0eb2Z7R/N3x/YUJwSRWKwaFHSFYjErpCrUAy4D1jl7rdnzXoUGBu9HgvMj788kZjoTkxJoe4FLHMS8C/AS2ZWH037HjAV+KWZfRv4GzCqOCWKxKC6OukKRGLXaoC7+x8ByzP7tHjLESkStcAlhXQnpoRBT6WXFFKASxgaG5OuQCR2CnAJg65CkRRSgEsYpk9PugKR2CnAJQwLFiRdgUjsFOAShjFjkq5AJHYKcAnDyJFJVyASOwW4hEEtcEkhBbiEwfLdiyZSuhTgEgb3pCsQiZ0CXMIwa1bSFYjETgEuYVi4MOkKRGKnAJcwqAUuKaQAlzCce27SFYjETgEuYdBwspJCCnAJw4gRSVcgEjsFuIRhwICkKxCJnQJcwrBlS9IViMROAS5h0HCykkIKcAlDXV3SFYjETgEuYVALXFJIAS5h0FUokkIKcAnD5MlJVyASOwW4hGHQoKQrEImdAlzCUF2ddAUisVOASxgaG5OuQCR2CnAJw7RpSVcgEjsFuIRBLXBJIQW4hEEtcEkhBbiEYciQpCsQiZ0CXMKgOzElhbonXYBI0U3uCxs/gQXdAD1aTdJDLXAJw6xtSVcgEjsFuIThX/skXYFI7BTgEoZFTUlXIBI7BbiISInSSUwJw4iyPc6unPSrXa/XTj2n2NWIxEItcAnDf25NugKR2LUa4GZ2v5ltMLMVWdP2NbMnzOy16Ptni1umSAeN6Z10BSKxK6QFPgM4u8W0ScCT7n4I8GT0XqTr2p50ASLxazXA3f1p4L0Wk88HZkavZwIXxFyXSLwW6jpwSZ/2nsT8vLu/DeDub5vZ5/ItaGa1QC3AQQcd1M7diXRQbeY68LVlY3LObj59cycUJNJxRT+J6e7T3b3a3av79+9f7N2J5PZbXQcu6dPeAF9vZvsDRN83xFeSSBGUW9IViMSuvQH+KDA2ej0WmB9POSJF8j96JV2BSOxa7QM3s9nACKCfmTUANwFTgV+a2beBvwGjilmkSCH2eDPOtC0wsbyTKxIprlYD3N1H55l1Wsy1iBRP7WeSrkAkdroTU8Kw8dOkKxCJnQJcwrBId/JI+ijAJQzj1IUi6aPRCCWdJvdt/n7BNjhX46FIuqgFLmEY0C3pCkRipwCXMAzpmXQFIrFTgEsYfvD3pCsQiZ0CXMJwrW7ikfTRSUxJjXwjDWZm7oBDe3ReMSKdQC1wCcOLHyddgUjsFOAShtF7JV2BSOwU4BKGhz5MugKR2CnAJQyD1P8t6aOTmNJl7XF42LY6qp0Bnn1H5+TNrU8X6URqgUsYbtZ14JI+CnAJw017J12BSOwU4BKGl3QZoaSP+sClS8nu9y5kmYL7xld/3P5+8NbsqT9cfeVSRGqBSxi+oevAJX0U4BKG2boOXNJHAS5hOE7XgUv6KMAlDJU63SPpo5/q1rR8NJdORCWu+aiDBX4et2+B6wu8lLDlZ94GLU/Cri1r96a6Bp2E7dLUApcwFBreIiVEAS5hWPpR0hWIxE4BLmFo/CTpCkRipwCXMJzbO+kKRGKnk5gdUcgJnriWySPWEfti0taami2fdYKysmlW6zsr9ITjjA9g3GcKW7YD+9rjY90KGdmw2fL/WKYzP+fmn0dRdyUdpBa4hGFEr6QrEImdAlzCsJ9+1CV99FMtYZj+QdIViMQu7D7wIt2kUIw+xIL6QLOOJ7v/uFm/bAH98M3WLWBfe9xuPlnr5/s3al532za/m4nlHdxAsvLdvJTv/EFBTw/KM32P/fjSpagFLmF4ZnvSFYjETgEuYdjiSVcgEjsFuIThLF0PJ+mjAJcwTN+adAUisSvNk5gduCEin4JvlMi7j+zpuW9AyXvCKc928p+IzF6hgJtd2lhDs5tpJuWpoaV8x9+Bkf1iNbKL3YnZkX+XAn7WOrbNDixT8P5a/3+b70augk7KN9tXPDfTFXTCuJOpBS5h0H08kkIdCnAzO9vMXjWz181sUlxFicRu1rakKxCJXbsD3My6AfcAXwGOAEab2RFxFSYSq3/tk3QFIrHrSAv8eOB1d/+Lu38EzAHOj6cskZgtakq6ApHYmXv7ro81swuBs939iuj9vwAnuPuEFsvVArXR20OBV9tfbiL6Ae8mXUQn0zGHQcdcOr7g7v1bTuzIVSiWY9puvw3cfTowvQP7SZSZ1bl7ddJ1dCYdcxh0zKWvI10oDcCBWe8rgMaOlSMiIoXqSIAvAQ4xs4Fm1hO4GHg0nrJERKQ17e5CcfcdZjYB+C3QDbjf3VfGVlnXUbLdPx2gYw6DjrnEtfskpoiIJEt3YoqIlCgFuIhIiVKA52Fm/8/MXjGz5Wb2iJntkzXv+mj4gFfN7Kwk64yTmY0ys5Vm9qmZVbeYl8pjhjCGhDCz+81sg5mtyJq2r5k9YWavRd8/m2SNcTKzA83sKTNbFf1MXx1NT9UxK8DzewI40t2PBlYD1wNEwwVcDAwGzgZ+HA0rkAYrgK8DT2dPTPMxBzQkxAwyn122ScCT7n4I8GT0Pi12ABPd/XCgBrgq+lxTdcwK8Dzc/XF33xG9fY7Mde6QGS5gjrtvd/c3gNfJDCtQ8tx9lbvnulM2tcdMIENCuPvTwHstJp8PzIxezwQu6NSiisjd33b3F6PXW4BVwAGk7JgV4IW5HPhN9PoA4M2seQ3RtDRL8zGn+dha83l3fxsygQd8LuF6isLMKoFjgedJ2TGX5gMdYmJmvwP+OcesG9x9frTMDWT+HHtg52o5li+ZazELOeZcq+WYVjLH3Io0H1vwzKwP8BBwjbv/3SzXx126gg5wdz99T/PNbCwwEjjN/3HBfEkPIdDaMedR0sfcijQfW2vWm9n+7v62me0PbEi6oDiZWQ8y4f2Auz8cTU7VMasLJQ8zOxu4DjjP3T/MmvUocLGZ9TKzgcAhwAtJ1NiJ0nzMIQ8J8SgwNno9Fsj3F1jJsUxT+z5glbvfnjUrVcesOzHzMLPXyTyIa2M06Tl3vzKadwOZfvEdZP40+03urZQWM/sa8J9Af+B9oN7dz4rmpfKYAczsq8Cd/GNIiO8nXFLszGw2MILMcKrrgZuA/wZ+CRwE/A0Y5e4tT3SWJDM7GVgMvAR8Gk3+Hpl+8NQcswJcRKREqQtFRKREKcBFREqUAlxEpEQpwEVESpQCXESkRCnARURKlAJcRKRE/X+jyMcp2TePqAAAAABJRU5ErkJggg==\n", "text/plain": [ "
" ] @@ -2269,45 +11610,47 @@ }, { "cell_type": "code", - "execution_count": 57, - "metadata": {}, + "execution_count": 54, + "metadata": { + "scrolled": false + }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "BR: 0.0000\n", - "1.0\n", + "0.696078431372549\n", "\n", "BR: 0.0001\n", - "1.0\n", + "0.7156862745098039\n", "\n", "BR: 0.0002\n", - "0.0\n", + "0.6274509803921569\n", "\n", "BR: 0.0003\n", - "1.0\n", + "0.6764705882352942\n", "\n", "BR: 0.0004\n", - "1.0\n", + "0.7549019607843137\n", "\n", "BR: 0.0005\n", - "1.5\n", + "0.7093596059113301\n", "\n", "BR: 0.0006\n", - "0.5\n", + "0.6108374384236454\n", "\n", "BR: 0.0007\n", - "0.0\n", + "0.6108374384236454\n", "\n", "BR: 0.0008\n", - "0.5\n", + "0.6896551724137931\n", "\n", "BR: 0.0009\n", - "0.5\n", + "0.6305418719211823\n", "\n", "BR: 0.0010\n", - "0.5\n", + "0.7586206896551724\n", "\n" ] } @@ -2315,17 +11658,47 @@ "source": [ "for s in range(len(l)):\n", " print('BR: {:.4f}'.format(BR_steps[s]))\n", - " print(2*l[s]/len(CLs_values[0]))\n", + " print(2*l[s]/len(CLs_values[s]))\n", " print()" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 53, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "297818.356392785\n", + "297819.7667433609\n", + "297840.3929684116\n", + "297842.76270291663\n", + "297824.18234748516\n", + "297824.15246830357\n", + "297805.96860094374\n", + "297805.6297383122\n", + "297815.3593473281\n", + "297816.9535084667\n", + "297813.1327635662\n", + "297813.25842232205\n", + "297822.5320305655\n", + "297823.22816647816\n", + "297826.72528264904\n", + "297826.3537664936\n", + "297836.0488055982\n", + "297836.00021670037\n", + "297815.56969196635\n", + "297815.8245172473\n", + "297814.9244276687\n", + "297816.06427965104\n" + ] + } + ], "source": [ - "# print(np.array(Nll_list[0][:10])-np.array(Nll_list[1][:10]))" + "for i in range(len(Nll_list)):\n", + " print(np.mean(np.array(Nll_list[i])))" ] }, { diff --git a/test++.png b/test++.png new file mode 100644 index 0000000..c26471d --- /dev/null +++ b/test++.png Binary files differ diff --git a/test+-.png b/test+-.png new file mode 100644 index 0000000..b93df58 --- /dev/null +++ b/test+-.png Binary files differ diff --git a/test-+.png b/test-+.png new file mode 100644 index 0000000..f7a5b6b --- /dev/null +++ b/test-+.png Binary files differ diff --git a/test--.png b/test--.png new file mode 100644 index 0000000..c26471d --- /dev/null +++ b/test--.png Binary files differ diff --git a/test.png b/test.png index 32ddf27..b93df58 100644 --- a/test.png +++ b/test.png Binary files differ